<?php
namespace Customer\Controllers;

use Admin\Models\bpm\XHBpmNode;
use Admin\Models\bpm\XHBpmPlan;
use Admin\Models\bpm\XHBpmPlanContent;
use Admin\Models\bpm\XHBpmTransList;
use Admin\Models\crm\XhcustAuth;
use Admin\Models\crm\XhcustClass;
use Admin\Models\crm\XhcustContact;
use Admin\Models\crm\XhcustContent;
use Admin\Models\ims\XHImsApplyTablet;
use Admin\Models\school\XhschoolInfo;
use Helpers\Assets;
use Helpers\Cache;
use Helpers\Hrm;
use Helpers\HttpClient;
use Helpers\Main;
use Helpers\PHPMailer;
use Helpers\Template;
use Admin\Models\crm\XhcustInfo;
use Admin\Models\crm\XhcustTrack;
use Admin\Models\overt\XhovertAreainfo;
use Admin\Models\sys\XhsysEnum;
use Admin\Models\user\XhsysUser;
use Admin\Models\hrm\XhhrmStaff;
use Helpers\Tool;
use Helpers\User;
use Helpers\UserPower;
use Modules\Power;
use Phalcon\Db\Adapter\Pdo\Mysql;

class CustomerController extends ControllerBase
{


    public static $stage = [1 => '小学', 2 => '初中', 3 => '高中'];

    public function notFoundAction()
    {
        return $this->response->setStatusCode(404)->setJsonContent(['code' => 404, 'error' => 'page not found!']);
    }


    public function extraPower($tag){
        if(User::isAdmin()){
            return true;
        }
        $deps = User::getExtraPower('dep',$tag);
        $userIds = Hrm::getUserByDepId($deps);
        $newArr = [];
        if ($userIds) {
            foreach ($userIds as $ids){
                $newArr =array_merge($newArr,$ids);
            }
            $newArr = array_values(array_filter(array_unique($newArr)));
        }
        return $newArr;
    }


    /**
     * 创建
     * @param $detail
     * @param $msg
     * @return bool
     * created by dale 2017/8/17
     */
    public function praseLog($detail,$msg){
        return Main::createCommitLog(
            'customer',
            $this->dispatcher->getControllerName(),
            $this->dispatcher->getActionName(),
            ['post'=>$this->request->getPost(),'get'=>$this->request->getQuery(),'detail'=>$detail],
            null,
            $msg
        );
    }

    /**
     * 枚举公共方法
     *
     * @return array
     * created by dale 2017/7/21
     */

    public static function getEnums()
    {
        return [
            'bCoop' => [0 => '否', 1 => '是'],
            'iType' => [0 => '意向学校', 1 => '合作学校', 2 => '前期接触',3=>'终止合作', 4 => '教育部门'],
            'bWelfare' => [0 => '否', 1 => '是'],
            'bAgree' => [0 => '否', 1 => '是'],
            'iLevel' => XhsysEnum::getEnumByNodeName('学校等级'),
            'iGrade' => XhsysEnum::getEnumByNodeName('年级'),
            'iChargeMode' => XhsysEnum::getEnumByNodeName('收费模式'),
            'iUsageMode' => XhsysEnum::getEnumByNodeName('使用模式'),
            'iGroupId' => XhsysEnum::getEnumByNodeName('客户组别'),
            'bDefault' => [0 => '否', 1 => '是'],
            'iContent' => XhsysEnum::getEnumByNodeName('意向内容'),
            'iAidsLevel'=>[1=>'低',2=>'中',3=>'高'],
        ];
    }

    //-------------------------------------------DataGrid Start-----------------------------------------------

    /**
     * 客户列表
     *
     * created by dale 2017627
     * modified by dale 2017721
     * modify by dale 20180324
     */
    public function customerListAction()
    {   //客户列表
        if(!UserPower::checkUserPower('Cust_List')){
            return $this->sendViewError('没有权限');
        }
        $enums = self::getEnums();
        $this->view->pick('customer/customerList');
        Assets::easyUI();
        Assets::select2();
        Assets::radialIndicator();
        Assets::sweetAlert2();
        Assets::importJs('js/customerList.js');
        Template::exists('customerList', 'list') or die(Main::showMessageModal('配置文件不存在，请先创建！', 109106002));//检查public/template/from/目录下是否都存在template文件夹
        $listButtonArr = $formButtonArr = $listSearchArr = array();
        if (UserPower::checkUserPower('Cust_List_Add')) {
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_add', 'text' => '增加', 'icon' => 'fa-plus');
        }
        $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_manage', 'text' => '设置权限', 'icon' => 'fa-pencil');
        if (UserPower::checkUserPower('Cust_List_Del')) {
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_del', 'text' => '删除', 'icon' => 'fa-trash');
        }
        if (Power::exist('Cust_List_SwapPower')) { // 权限交接
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_swapPower', 'text' => '交接权限', 'icon' => 'fa-refresh');
        }
        $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_menu', 'text' => '更多', 'class'=>'bt_list_menu');

        $enums['iType'][''] = '--学校类型--';
        $enums['bAgree'][''] = '--是否签署协议--';
        $enums['iGroupId'][''] = '--组别--';
        $listSearchArr[] = array('type' => 'select', 'id' => 'select_type', 'data' => $enums['iType'], 'default' => '');
        $listSearchArr[] = array('type' => 'select', 'id' => 'select_agree', 'data' => $enums['bAgree'], 'default' => '');
        $listSearchArr[] = array('type' => 'select', 'id' => 'select_group', 'data' => $enums['iGroupId'], 'default' => '');

        $enums['province'] = array_column(array_values($this->getAreaByLevel(1)),'areaName','areaCode');
        $enums['province'][''] = '--请选择省--';
        $listSearchArr[] = array('type' => 'select', 'id' => 'select_province', 'data' => $enums['province'], 'default' => '');
        $enums['city'][''] = '--请选择市--';
        $listSearchArr[] = array('type' => 'select', 'id' => 'select_city', 'data' => $enums['city'], 'default' => '');
        $enums['county'][''] = '--请选择县--';
        $listSearchArr[] = array('type' => 'select', 'id' => 'select_county', 'data' => $enums['county'], 'default' => '');

        $listSearchArr[] = array('type' => 'text', 'id' => 'list_search', 'label' => ' 搜索： ');
        $listSearchArr[] = array('type' => 'button', 'id' => 'bt_list_search', 'text' => '查找', 'icon' => 'fa-search', 'style' => 'margin-left:10px');
        $listSearchArr[] = array('type' => 'button', 'id' => 'excel_export', 'text' => '导出', 'icon' => 'fa fa-file-excel-o');
        $listSearchArr[] = array('type' => 'button', 'id' => 'bt_list_export_plan', 'text' => '导出客户状态', 'icon' => 'fa fa-file-excel-o');

        $this->view->setVars(array(
            'List'   => Template::createList('List', 'customerList', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, true),
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr)
            ]),
            'planAdd' => UserPower::checkUserPower('Bpm_Plan_Add'),
            'market'   => Hrm::getDepStaffByTag('XHSCB'),
        ));
    }

    /**
     * 权限交接
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by xjq 20180710
     */
    public function swapPowerAction()
    {
        try{
            $this->db->begin();
            if (!Power::exist('Cust_List_SwapPower')){
                return $this->sendErrorResponse(401, '没有权限');
            }
            $iCUIdArr = $this->request->getPost('iCUIdArr', 'int');
            $date     = $this->request->getPost('date', 'string');
            $userId   = $this->request->getPost('userId','int');
            if(!$iCUIdArr || !$date || !$userId){
                return $this->sendErrorResponse(500, '缺少参数');
            }
            $objArr = XhcustInfo::find([
                'conditions' =>  'bDelete = 0 and iCUId in ({ids:array})',
                'bind'       => ['ids' => $iCUIdArr]
            ]);
            $nowUserId = Main::getLoginUserInfo('userId');
//            if (!User::isAdmin()) {
//                foreach ($objArr as $obj) {
//                    if ($obj->iCreateUserId != $nowUserId) {
//                        return $this->sendErrorResponse(400, '部分记录并非你创建，无法交接');
//                    }
//                }
//            }
            foreach ($objArr as $obj) {
                $arr   = $obj->mHistoryCreator;
                $arr[] = ['date' => $date, 'originUserId' => $obj->iCreateUserId, 'nowUserId' =>$userId, 'modifyDate' => date('Y-m-d H:i:s'),'modifyUserId'=>$nowUserId];
                $obj->mHistoryCreator = $arr;
                $obj->iCreateUserId = $userId;
                if (!$obj->save()) {
                    $this->db->rollback();
                    return $this->sendErrorResponse(500, '保存失败');
                }
            }
            $this->db->commit();
            return $this->sendSuccessResponse('权限交接成功');
        }catch (\Exception $e){
            $this->db->rollback();
            return $this->sendErrorResponse(500 ,$e->getMessage());
        }
    }

    /**
     * 获取地区等级
     *
     * @param $level
     * @return array
     *
     * create by dale 20180402
     */
    public function getAreaByLevel($level)
    {
        $area = XhovertAreainfo::find([
            'conditions' => ' areaLevel = :level:',
            'bind'       => ['level'=> $level ]
        ])->toArray();
        $area = array_column($area,null,'areaCode');
        return $area;
    }

    /**
     * 获取地址通过父类城市id
     *
     * @param $id
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale 20180427
     */
    public function getAreaByIdAction($id=null)
    {
        if($id){
            $area = XhovertAreainfo::find([
                'conditions' => ' parentCode = :parentCode:',
                'bind'       => ['parentCode'=> $id ]
            ])->toArray();
            if(isset($area[0]['areaLevel']) ){
                if($area[0]['areaLevel'] == 2){
                    $area[] = ['areaName'=>'--请选择市--','areaCode'=>''];
                }else{
                    $area[] = ['areaName'=>'--请选择县--','areaCode'=>''];
                }
            }
            return $this->sendJsonResponse($area);
        }

    }


    /**
     * 联系人列表
     *
     * created by dale 2017/8/7
     * modify by dale 20180324
     */
    public function contactAction()
    {
        if(!UserPower::checkUserPower('Cust_List_Contact')){
            return $this->sendViewError('没有权限');
        }
        $this->view->pick('customer/contact');
        Assets::easyUI();
        Assets::select2();
        Assets::importMainJs('assets/xh/xhForm.js');
        Assets::importJs('js/myMain.js');
        Assets::importMainJs('assets/xh/xhDatagrid.js');
        Assets::importJs('js/contact.js');
        Template::exists('contact', 'list') or die(Main::showMessageModal('配置文件不存在，请先创建！', 109106002));//检查public/template/from/目录下是否都存在template文件夹
        $listButtonArr = $formButtonArr = $listSearchArr = array();
        if (UserPower::checkUserPower('Cust_List_Contact_Add')) {
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_add', 'text' => '增加', 'icon' => 'fa-plus');
        }
        if (UserPower::checkUserPower('Cust_List_Contact_Del')) {
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_del', 'text' => '删除', 'icon' => 'fa-trash');
        }
        if (UserPower::checkUserPower('Cust_List_Contact_Bind')) {
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_bindAccount', 'text' => '绑定账号', 'icon' => 'fa-pencil');
        }

        $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_setDefault', 'text' => '设为默认', 'icon' => 'fa-chain');
        $this->view->setVars(array(
            'List' => Template::createList('List', 'contact', [
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr)
            ]),
        ));
    }

    /**
     * 联系人表单
     *
     * created by dale 2017/8/10
     */
    public function contactFormAction()
    {
        $id = $this->request->getQuery('icucId', 'string');
        if ($id) {
            if(!UserPower::checkUserPower('Cust_List_Contact_Edit')){
                return $this->sendViewError('没有权限');
            }
        } else {
            if(!UserPower::checkUserPower('Cust_List_Contact_Add')){
                return $this->sendViewError('没有权限');
            }
        }
        Assets::select2();
        Assets::importMainJs('assets/xh/xhForm.js');
        Assets::importJs('js/myMain.js');
        Assets::importJs('js/contactForm.js');
        $this->view->pick('customer/contactForm');
        $this->view->setVars([
            'subject' => XhsysEnum::getEnumByNodeName('学科'),
            'grade'   => XhsysEnum::getEnumByNodeName('年级'),
            'duty'    => XhsysEnum::getEnumByNodeName('学校职位')
        ]);
    }

    /**
     * 绑定账号
     *
     * created by dale 2017125
     * modify by dale 20180324
     */
    public function bindAccountAction(){
        $this->view->pick('customer/bindAccount');
        Assets::importJs('js/bindAccount.js');
        $iCUCId = $this->request->getQuery('iCUCId', 'int');
        if (!$iCUCId) {
            return $this->sendViewError('缺少联系人id！');
        }
        $contact = XhcustContact::findFirst($iCUCId);
        if (!$contact) {
            return $this->sendViewError('找不到联系人记录！');
        }
        if($contact->sPhoneNum == null){
            return $this->sendViewError('电话为空！');
        }
        $params = [
            'columns' => 'iUserId,sUserName,sLogonName,sSelfPhone,bDisable',
            'conditions' => 'sSelfPhone = :phoneNum: OR sLogonName = :phoneNum:',
            'bind' => ['phoneNum' => $contact->sPhoneNum]
        ];
        if ($contact->iUserId) {
            $params['conditions'] .= ' OR iUserId = :userId:';
            $params['bind']['userId'] = $contact->iUserId;
        }
        $userList = XhsysUser::find($params)->toArray();
        if (!$userList) {
            return $this->sendViewError('找不到联系人所属账号!');
        }
        if ($contact->iUserId) {
            foreach ($userList as $index => $user) {
                if ($contact->iUserId == $user['iUserId']) {
                    $userList[$index]['sUserName'] .= "<font style='color: red;'>(已绑定)</font>";
                }
            }
        }
        return $this->view->setVar('accountList', $userList);
    }

    /**
     * 保存绑定
     * @param bool $bind
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * create by dale 20180324
     */
    public function saveBindAction($bind = false)
    {
        try{
            $iCUCId = $this->request->getPost('iCUCId', 'int');
            $userId = $this->request->getPost('userId', 'int');
            if (!$iCUCId || !$userId) {
                return $this->sendErrorResponse(400,'缺少参数');
            }
            $contact = XhcustContact::findFirst($iCUCId);
            if (!$contact) {
                return $this->sendErrorResponse(500,'找不到联系人');
            }
            if ($bind) {
                if ($userId != $contact->iUserId) {
                    return $this->sendErrorResponse(500,'该记录未关联');
                }
                $contact->iUserId = null;
            } else {
                $contact->iUserId = $userId;
            }
            if (!$contact->save()) {
                return $this->sendErrorResponse(500,'保存失败');
            }
            return $this->sendSuccessResponse('保存成功');

        }catch (\Exception $e){
            return $this->sendErrorResponse(500,$e->getMessage());
        }
    }



    /**
     * 获取联系人信息(1条或者多条,过滤,搜索)
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface|string
     *
     *  created by dale 201787
     *  modify by dale 20180324
     */
    public function getContactDataAction()
    {
        $iCUId = $this->request->getQuery('id');
        $iCUCId = $this->request->getPost('iCUCId');
        $key = $this->request->getPost('key');
        $sort = $this->request->getPost('sort', 'string');
        $order = $this->request->getPost('order', 'string');
        $enums = self::getEnums();
        $parameters = [
            'conditions' => 'bDelete=:bDelete:',
            'bind' => ['bDelete' => 0],
        ];
        if ($iCUCId) {
            $parameters['conditions'] .= "AND iCUCId=:iCUCId:";
            $parameters['bind'] = array_merge($parameters['bind'], array('iCUCId' => $iCUCId));
            $obj = XhcustContact::findFirst($parameters);
            return json_encode($obj->toArray());
        }
        if ($iCUId) {
            $parameters['conditions'] .= "AND iCUId=:iCUId:";
            $parameters['bind'] = array_merge($parameters['bind'], array('iCUId' => $iCUId));
        }
        if ($key) {
            $parameters['conditions'] .= "AND (sName like :key: OR sJob like :key:)";
            $parameters['bind'] = array_merge($parameters['bind'], array('key' => '%' . $key . '%'));
        }
        if ($sort && $order) {
            $parameters['order'] = $sort . " " . strtoupper($order);
        }
        $data = Main::runModelPaginator('Admin\Models\crm\XhcustContact', $parameters, true);
        $enums = ['sSubjects'=> XhsysEnum::getEnumByNodeName('学科') , 'sGrades' => XhsysEnum::getEnumByNodeName('年级'),
                  'iDuty'=>XhsysEnum::getEnumByNodeName('学校职位'),'bCharge' => [1=>'是',0=>'否']];
        foreach ($data['rows'] as $index => $obj) {
            $data['rows'][$index]['bDefault']  = $enums['bDefault'][$obj['bDefault']];
            $data['rows'][$index]['sSubjects'] = $this->runEnums($obj['sSubjects'],$enums['sSubjects']);
            $data['rows'][$index]['sGrades']   = $this->runEnums($obj['sGrades'],$enums['sGrades']);
            $data['rows'][$index]['iDuty']     = $this->runEnums($obj['iDuty'],$enums['iDuty']);
            $data['rows'][$index]['bCharge']   = $this->runEnums($obj['bCharge'],$enums['bCharge']);
            if($obj['iUserId'] != null){
                $data['rows'][$index]['info'] = '<i class="fa fa-user" style="color:#2baab1;" title="'.$obj['iUserId'].'"></i>';
            }else{
                $data['rows'][$index]['info'] = '';
            }
        }
        Main::runUserNameById($data['rows'], 'iLastModifyUserId', true);
        Main::runUserNameById($data['rows'], 'iCreateUserId', true);
        return $this->response->setContent(json_encode($data, JSON_UNESCAPED_UNICODE));
    }

    /**
     * 处理枚举
     *
     * @param $fields
     * @param $enum
     * @return string
     * create by dale 20180308
     */
    public function runEnums($fields,$enum){
        $fields = array_values(array_filter(explode(',',$fields)));
        $arr = [];
        foreach ($fields as $field){
            $arr[] = $enum[$field];
        }
        return implode(',',$arr);
    }

    /**
     * 保存联系人信息(编辑,添加)
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * created by dale 2017/8/7
     * modify by dale 20180324
     */
    public function saveContactAction()
    {
        try{
            $iCUCId = $this->request->getPost('iCUCId', 'string');
            $iCUId = $this->request->getPost('iCUId', 'string') or die('缺少参数');
            $sSubjects = $this->request->getPost('sSubjects');
            $sGrades   = $this->request->getPost('sGrades');
            if ($iCUCId == null) {
                $obj = new XhcustContact();
            } else {
                $obj = XhcustContact::findFirst($iCUCId);
            }
            $obj->assign($this->request->getPost());
            //检查是否是第一条
            $check = XhcustContact::findFirst([
                'conditions' => 'bDelete=:bDelete: AND iCUId=:iCUId:',
                'bind' => ['bDelete' => 0, 'iCUId' => $iCUId],
            ]);
            if (!$check) {
                $obj->bDefault = 1;
            }
            $obj->sSubjects = isset($sSubjects) ? implode(',',$sSubjects) : null ;
            $obj->sGrades   = isset($sGrades)   ? implode(',',$sGrades)   : null ;
            $result = $obj->save();
            if ($result) {
                if ($obj->bDefault == 1) {
                    $info = XhcustInfo::findFirst([
                        'conditions' => 'bDelete=:bDelete: AND iCUId=:iCUId:',
                        'bind' => ['bDelete' => 0, 'iCUId' => $iCUId],
                    ]);
                    $info->sChargeName = $obj->sName;
                    $info->sChargePhone = $obj->sPhoneNum;
                    if ($info->save()) {
                        return json_encode($obj->toArray());
                    } else {

                        return $this->sendErrorResponse(500,'第一个默认联系人保存失败');
                    }
                }

                return $this->sendSuccessResponse('保存成功');
            } else {
                return $this->sendSuccessResponse(500,'保存失败');
            }
        }catch (\Exception $e){
            return $this->sendErrorResponse(500,$e->getMessage());
        }

    }

    /**
     * 改变默认
     *
     * @return string
     * created by dale 2017/8/10
     * modify by dale 20180324
     */
    public function changeDefaultAction()
    {
        try{
            $iCUCId = $this->request->getPost('iCUCId', 'string') ;
            $iCUId  = $this->request->getPost('iCUId', 'string') ;
            if(!$iCUCId || !$iCUId){
                return $this->sendErrorResponse(400,'缺少参数');
            }
            $contact = XhcustContact::findFirst([
                'conditions' => 'bDelete=:bDelete: AND iCUCId=:iCUCId:',
                'bind' => ['bDelete' => 0, 'iCUCId' => $iCUCId],
            ]);
            if ($contact->bDefault == 1) {
                return $this->sendErrorResponse(400,'已经是默认联系人不需要在设置');
            }
            $this->db->begin(); //开启事务
            $objs = XhcustContact::find([
                'conditions' => 'bDelete=:bDelete: AND iCUId=:iCUId:',
                'bind' => ['bDelete' => 0, 'iCUId' => $iCUId],
            ]);
            if ($objs) {
                foreach ($objs as $obj) {
                    $obj->bDefault = 0;
                    if (!$obj->save()) {
                        $this->db->rollback();
                        return  $this->sendErrorResponse(500,'取消其他联系人失败');
                    }
                }
            }
            $contact->bDefault = 1;
            if (!$contact->save()) {
                $this->db->rollback();
                return $this->sendErrorResponse(500,'设置默认失败');
            }
            $info = XhcustInfo::findFirst([
                'conditions' => 'bDelete=:bDelete: AND iCUId=:iCUId:',
                'bind' => ['bDelete' => 0, 'iCUId' => $iCUId],
            ]);
            $info->sChargeName = $contact->sName;
            $info->sChargePhone = $contact->sPhoneNum;
            if (!$info->save()) {
                return $this->sendErrorResponse(500,'更新失败');
            }
            $this->db->commit();
            return $this->sendSuccessResponse('更新成功');
        }catch (\Exception $e){
            $this->db->rollback();
            return $this->sendErrorResponse(500,$e->getMessage());
        }

    }

    /**
     * 创建账号
     *
     * created by dale 2017126
     */
    public function createAccountAction(){
        try{
            $userName = $this->request->getPost('userName','string');
            $phoneNum = $this->request->getPost('phoneNum','string');
            $schoolId = $this->request->getPost('schoolId','int');
            if(!$userName || !$phoneNum){
                return $this->sendErrorResponse(400,'缺少参数');
            }
                $res = $this->createNewAccount($phoneNum,$userName,intval($schoolId));
            if($res){
                return $this->sendSuccessResponse('保存成功');
            }else{
                return $this->sendErrorResponse(500,'失败');
            }
        }catch (\Exception $e){
            return $this->sendErrorResponse(500,$e->getMessage());
        }

    }

    /**
     * 根据手机号，用户姓名创建账号
     *
     * @param $phoneNum
     * @param $staffName
     * @param string $pwd
     * @param $schoolId
     * @return bool
     * @throws \Exception
     *
     * create by ck 20171113
     */
    private function createNewAccount($phoneNum, $staffName,$schoolId, $pwd = '123456')
    {
        $user = new XhsysUser();
        $user->sLogonName   = $phoneNum;
        $user->sUserName    = $staffName;
        $user->sLogonPwd    = strtoupper(md5($pwd));
        $user->sSelfPhone   = $phoneNum;
        $user->iUserType    = 4;
        $user->iSchoolId    = $schoolId;
        return $user->insertAfterOld();
//        static $httpClient;
//        if (!$httpClient) {
//            $url = Main::getConfigByName('hrm')['registerUrl'];
//            if (!$url) {
//                throw new \Exception('缺少registerUrl配置');
//            }
//            $httpClient = new HttpClient($url);
//        }
//        $response = $httpClient->post('main/register-staff', ['K' => json_encode(['sSelfPhone' => $phoneNum, 'sUserName' => $staffName, 'sLogonPwd' => strtoupper(md5($pwd)),'iSchoolId'=>$schoolId,'iUserType'=>4])]);
//        if (!$response->isSuccess()) {
//            throw new \Exception('请求失败：' . $response->error);
//        }
//        $body = $response->toArray();
//        if ($body['R'] != 200) {
//            throw new \Exception($body['M'] ?: $response->body);
//        }
//        return true;
    }


    /**
     * 删除联系人信息
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * created by dale 2017/8/7
     * modify by dale 20180324
     */
    public function delContactAction()
    {
        if(!UserPower::checkUserPower('Cust_List_Contact_Del')){
            return $this->sendErrorResponse(400,'缺少权限');
        }
        try{
            $ids = $this->request->getPost('ids', 'string');
            if(!$ids){
                return $this->sendErrorResponse(400,'缺少参数');
            }
            $ids = explode(',', $ids);
            $objs = XhcustContact::find([
                'conditions' => 'iCUCId in ({ids:array})',
                'bind' => ['ids' => $ids]
            ]);
            $this->db->begin();
            foreach ($objs as $obj) {
                $obj->bDelete = 1;
                if(!$obj->save()){
                    $this->db->rollback();
                    return $this->sendErrorResponse(500,'删除失败');
                }
            }
            $this->db->commit();
            return $this->sendSuccessResponse('保存成功');
        }catch (\Exception $e){
            return $this->sendErrorResponse(500,$e->getMessage());
        }

    }


    /**
     * 所有客户信息
     *
     * @return string 客户信息
     * created by dale 2017/6/27
     */
    public function getDataAction()
    {
        if(!UserPower::checkUserPower('Cust_List')){
            return $this->sendErrorResponse(400,'权限不足');
        };
        $enums = self::getEnums();
        $key = $this->request->getPost('key', 'string'); //可以为空
        $iType = $this->request->getPost('iType', 'string');
        $agree = $this->request->getPost('agree', 'string');
        $group = $this->request->getPost('group', 'string');
        $sort = $this->request->getPost('sort', 'string');
        $order = $this->request->getPost('order', 'string');
        $province = $this->request->getPost('province','string');
        $city     = $this->request->getPost('city','string');
        $county   = $this->request->getPost('county','string');
        try{
            $parameters = array(
                'conditions' => "bDelete=:bDelete:",
                'bind' => array('bDelete' => 0)
            );


            if ($key != null) {
                $parameters['conditions'] .= "AND (sSchoolName like :key: OR sIntroName like :key:
                                       OR sChargeName like :key: OR sDetailedAddress like :key: OR sProvinceName like :key:
                                       OR sCityName like :key:  OR sCountyName like :key:)";
                $parameters['bind'] = array_merge($parameters['bind'], array('key' => '%' . $key . '%'));
            }
            if ($iType != null) {
                $parameters['conditions'] .= "AND iType =:iType:";
                $parameters['bind'] = array_merge($parameters['bind'], array('iType' => $iType));
            }
            if ($agree != null) {
                $parameters['conditions'] .= "AND bAgree =:bAgree:";
                $parameters['bind'] = array_merge($parameters['bind'], array('bAgree' => $agree));
            }
            if ($group != null) {
                $parameters['conditions'] .= "AND iGroupId =:iGroupId:";
                $parameters['bind'] = array_merge($parameters['bind'], array('iGroupId' => $group));
            }

            if ($province && $province != '--请选择省--') {
                $parameters['conditions'] .= "AND sProvinceName =:province:";
                $parameters['bind'] = array_merge($parameters['bind'], array('province' => $province));
            }

            if ($city && $city != '--请选择市--') {
                $parameters['conditions'] .= "AND sCityName =:city:";
                $parameters['bind'] = array_merge($parameters['bind'], array('city' => $city));
            }

            if ($county && $county != '--请选择县--') {
                $parameters['conditions'] .= "AND sCountyName =:county:";
                $parameters['bind'] = array_merge($parameters['bind'], array('county' => $county));
            }

            if(!User::isAdmin()){
                $conditionsArr = [
                    'conditions' =>[],
                    'bind'       =>[],
                ];
                $iAuthId = Main::getLoginUserInfo('userId');
                $auth = XhcustAuth::find([
                    'conditions' => 'bDelete=0 AND iAuthId=:iAuthId:',
                    'bind' => array('iAuthId' => $iAuthId)
                ])->toArray();
                if (count($auth) > 0) { //
                    $arr = array_column($auth,'iCUId');
                    $conditionsArr['conditions'][] = "  iCUId in ({ids:array}) ";
                    $conditionsArr['bind'] = array_merge($conditionsArr['bind'], array('ids' => $arr));
                }
                $conditionsArr['conditions'][] = " iCreateUserId=:iCreateUserId: ";
                $conditionsArr['bind'] = array_merge($conditionsArr['bind'], array('iCreateUserId' => $iAuthId));

                if(User::getExtraPower('dep','customer',null,true)){ //有扩展权限
                    $userIds = $this->extraPower('customer');
                    if ($userIds){
                        $conditionsArr['conditions'][] = "iCreateUserId in ({userIds:array}) ";
                        $conditionsArr['bind'] = array_merge($conditionsArr['bind'], array('userIds' => $userIds));
                    }
                }

                $parameters['conditions'] .= "AND ( ".implode(' OR ',$conditionsArr['conditions'])." )";
                $parameters['bind']        = array_merge($parameters['bind'],$conditionsArr['bind']);

            }


            if ($sort && $order) {
                $parameters['order'] = $sort . " " . strtoupper($order);
            }


            $data = Main::runModelPaginator('Admin\Models\crm\XhcustInfo', $parameters, true);

            $ids=[];
            foreach ($data['rows'] as $index => $row){
                $ids[]=$row['iCUId'];
            }
            if(count($ids) > 0){
                $plans=XHBpmPlan::find([
                    'columns'=>'iBPPId,iCUId',
                    'conditions'=>'bDelete=0 AND iCUId in ({ids:array}) and bFinish = 0',
                    'bind'=>array('ids'=>$ids),
                    'order'=>'tCreateDate Desc'
                ]);
                $items=[];
                foreach ($plans as $plan){
                    foreach ($ids as $id){
                        if($plan->iCUId==$id){
                            $items[$plan->iCUId][]=$plan->toArray();
                        }
                    }
                }
            }
            $staffEnum['iMarketIds']       = Hrm::getDepStaffByTag('xhscb');
            $staffEnum['iOperateIds']      = Hrm::getDepStaffByTag('xhyyb');

            foreach ($data['rows'] as $index => $obj) {
                if(count($ids) > 0) {
                    $item = ($items[$obj['iCUId']] == null ? null : $items[$obj['iCUId']]);
                    if ($item != null) {
                        $pCount = count($item);
                        $obj['fileInfo'] = '<a id="file-' . $obj['iCUId'] . '-' . $item[0]['iBPPId'] . '"><i class="fa fa-file" title="' . $pCount . '" style="color:#2baab1;"></i></a>';
                    } else {
                        $obj['fileInfo'] = '';
                    }
                }
                if($obj['iSchoolId']!=null){
                    $obj['schoolIdInfo']='<a ><i class="fa fa-link" title="'.$obj['iSchoolId'].'" style="color:#2baab1;"></i></a>';
                }else{
                    $obj['schoolIdInfo']='';
                }
                $obj['iLevel'] = $enums['iLevel'][$obj['iLevel']];
                $obj['iType'] = $enums['iType'][$obj['iType']];
                $obj['bAgree'] = $enums['bAgree'][$obj['bAgree']];
                $obj['iGroupId'] = $enums['iGroupId'][$obj['iGroupId']];
                $obj['iAidsLevel'] = $enums['iAidsLevel'][$obj['iAidsLevel']];

                $obj['iMarketId']    = $staffEnum['iMarketIds'][$obj['iMarketId']] ?: '';
                $obj['iOperateId']   = $staffEnum['iOperateIds'][$obj['iOperateId']] ?: '';
                $obj['infoComplete'] = $this->custCompleteCheck($obj);
                $obj['canvasHtml']   = '<div class="prg-cont rad-prg" id="indicatorContainer_'.$obj['iCUId'].'" title="基本信息填写完成度：'.$obj['infoComplete'].'%"></div>';
                $data['rows'][$index] = $obj;
            }

            Main::runUserNameById($data['rows'], ['iLastModifyUserId' => 'iLastModifyUserId', 'iCreateUserId' => 'iCreateUserId'], true);
            return $this->sendJsonResponse($data);

        }catch (\Exception $e){
            return $this->sendErrorResponse(500,$e->getMessage());
        }
    }

    /**
     * @throws \PHPExcel_Exception
     * @throws \PHPExcel_Reader_Exception
     *
     */
    public function exportCustomerListAction()
    {
        $this->view->disable();
        UserPower::checkUserPower('Cust_List') or die('权限不足');
        $enums = self::getEnums();

        $key = $this->request->getQuery('key', 'string'); //可以为空
        $iType = $this->request->getQuery('iType', 'string');
        $agree = $this->request->getQuery('agree', 'string');
        $group = $this->request->getQuery('group', 'string');

        $province = $this->request->getQuery('province','string');
        $city     = $this->request->getQuery('city','string');
        $county   = $this->request->getQuery('county','string');

        $parameters = array(
            'conditions' => "bDelete=:bDelete:",
            'bind' => array('bDelete' => 0)
        );
        if ($key != null) {
            $parameters['conditions'] .= "AND (sSchoolName like :key: OR sIntroName like :key:
                                       OR sChargeName like :key: OR sDetailedAddress like :key: OR sProvinceName like :key:
                                       OR sCityName like :key:  OR sCountyName like :key:)";
            $parameters['bind'] = array_merge($parameters['bind'], array('key' => '%' . $key . '%'));
        }
        if ($iType != null) {
            $parameters['conditions'] .= "AND iType =:iType:";
            $parameters['bind'] = array_merge($parameters['bind'], array('iType' => $iType));
        }
        if ($agree != null) {
            $parameters['conditions'] .= "AND bAgree =:bAgree:";
            $parameters['bind'] = array_merge($parameters['bind'], array('bAgree' => $agree));
        }
        if ($group != null) {
            $parameters['conditions'] .= "AND iGroupId =:iGroupId:";
            $parameters['bind'] = array_merge($parameters['bind'], array('iGroupId' => $group));
        }

        if ($province && $province != '--请选择省--') {
            $parameters['conditions'] .= "AND sProvinceName =:province:";
            $parameters['bind'] = array_merge($parameters['bind'], array('province' => $province));
        }

        if ($city && $city != '--请选择市--') {
            $parameters['conditions'] .= "AND sCityName =:city:";
            $parameters['bind'] = array_merge($parameters['bind'], array('city' => $city));
        }


        if ($county && $county != '--请选择县--') {
            $parameters['conditions'] .= "AND sCountyName =:county:";
            $parameters['bind'] = array_merge($parameters['bind'], array('county' => $county));
        }


        if(!User::isAdmin()){
            $conditionsArr = [
                'conditions' =>[],
                'bind'       =>[],
            ];
            $iAuthId = Main::getLoginUserInfo('userId');
            $auth = XhcustAuth::find([
                'conditions' => 'bDelete=0 AND iAuthId=:iAuthId:',
                'bind' => array('iAuthId' => $iAuthId)
            ])->toArray();
            if (count($auth) > 0) { //
                $arr = array_column($auth,'iCUId');
                $conditionsArr['conditions'][] = "  iCUId in ({ids:array}) ";
                $conditionsArr['bind'] = array_merge($conditionsArr['bind'], array('ids' => $arr));
            }
            $conditionsArr['conditions'][] = " iCreateUserId=:iCreateUserId: ";
            $conditionsArr['bind'] = array_merge($conditionsArr['bind'], array('iCreateUserId' => $iAuthId));

            if(User::getExtraPower('dep','customer',null,true)){ //有扩展权限
                $userIds = $this->extraPower('customer');
                if ($userIds){
                    $conditionsArr['conditions'][] = "iCreateUserId in ({userIds:array}) ";
                    $conditionsArr['bind'] = array_merge($conditionsArr['bind'], array('userIds' => $userIds));
                }
            }


            $parameters['conditions'] .= "AND ( ".implode(' OR ',$conditionsArr['conditions'])." )";
            $parameters['bind']        = array_merge($parameters['bind'],$conditionsArr['bind']);
        }

        $source = XhcustInfo::find($parameters)->toArray();
        foreach ($source as $index => $obj) {
            $obj['iLevel'] = $enums['iLevel'][$obj['iLevel']];
            $obj['iType'] = $enums['iType'][$obj['iType']];
            $obj['bWelfare'] = $enums['bWelfare'][$obj['bWelfare']];
            $obj['bAgree'] = $enums['bAgree'][$obj['bAgree']];
            $obj['iGroupId'] = $enums['iGroupId'][$obj['iGroupId']];
            $source[$index] = $obj;
        }
        Main::runUserNameById($source, 'iLastModifyUserId', true);
        Main::runUserNameById($source, 'iCreateUserId', true);

        $title = [
            'sSchoolName' => '学校名称',
            'iType' => '类型',
            'iLevel' => '等级',
            'tSchoolDate' => '办校时间',
            'bAgree' => '协议',
            'bWelfare' => '公益',
            'iGroupId' => '组别',
            'sMarketName' => '市场负责人',
            'sOperationName' => '运营负责人',
            'sIntroName' => '介绍人姓名',
            'sChargeName' => '负责人姓名',
            'sChargePhone' => '负责人电话',
            'sProvinceName' => '所在省',
            'sCityName' => '所在市',
            'sCountyName' => '所在区',
            'sDetailedAddress' => '详细地址',
            'tCreateDate' => '创建时间',
            'iCreateUserId' => '创建用户',
            'tLastModifyDate' => '最后修改时间',
            'iLastModifyUserId' => '最后修改用户',
        ];
        $data = [];
        foreach ($source as $key => $row) {
            foreach ($title as $filed => $name) {
                $data[$key][$filed] = isset($row[$filed]) ? $row[$filed] : '';
            }
        }
        $fileName = '客户列表_' . Main::getLoginUserInfo('userName');
        $this->praseLog('导出客户列表','导出客户列表');
        Tool::exportExcelOnline($fileName, $title, $data);
    }

    public function exportCustomerPlanAction()
    {
        $this->view->disable();
        $key = $this->request->getQuery('key', 'string'); //可以为空
        $iType = $this->request->getQuery('iType', 'string');
        $agree = $this->request->getQuery('agree', 'string');
        $group = $this->request->getQuery('group', 'string');

        $province = $this->request->getQuery('province','string');
        $city     = $this->request->getQuery('city','string');
        $county   = $this->request->getQuery('county','string');
        try{
            $enums = self::getEnums();
            $parameters = array(
                'conditions' => "bDelete=:bDelete:",
                'bind' => array('bDelete' => 0)
            );
            if ($key != null) {
                $parameters['conditions'] .= "AND (sSchoolName like :key: OR sIntroName like :key:
                                       OR sChargeName like :key: OR sDetailedAddress like :key: OR sProvinceName like :key:
                                       OR sCityName like :key:  OR sCountyName like :key:)";
                $parameters['bind'] = array_merge($parameters['bind'], array('key' => '%' . $key . '%'));
            }
            if ($iType != null) {
                $parameters['conditions'] .= "AND iType =:iType:";
                $parameters['bind'] = array_merge($parameters['bind'], array('iType' => $iType));
            }
            if ($agree != null) {
                $parameters['conditions'] .= "AND bAgree =:bAgree:";
                $parameters['bind'] = array_merge($parameters['bind'], array('bAgree' => $agree));
            }
            if ($group != null) {
                $parameters['conditions'] .= "AND iGroupId =:iGroupId:";
                $parameters['bind'] = array_merge($parameters['bind'], array('iGroupId' => $group));
            }

            if ($province && $province != '--请选择省--') {
                $parameters['conditions'] .= "AND sProvinceName =:province:";
                $parameters['bind'] = array_merge($parameters['bind'], array('province' => $province));
            }

            if ($city && $city != '--请选择市--') {
                $parameters['conditions'] .= "AND sCityName =:city:";
                $parameters['bind'] = array_merge($parameters['bind'], array('city' => $city));
            }


            if ($county && $county != '--请选择县--') {
                $parameters['conditions'] .= "AND sCountyName =:county:";
                $parameters['bind'] = array_merge($parameters['bind'], array('county' => $county));
            }

            if(!User::isAdmin()){
                $conditionsArr = [
                    'conditions' =>[],
                    'bind'       =>[],
                ];
                $iAuthId = Main::getLoginUserInfo('userId');
                $auth = XhcustAuth::find([
                    'conditions' => 'bDelete=0 AND iAuthId=:iAuthId:',
                    'bind' => array('iAuthId' => $iAuthId)
                ])->toArray();
                if (count($auth) > 0) { //
                    $arr = array_column($auth,'iCUId');
                    $conditionsArr['conditions'][] = "  iCUId in ({ids:array}) ";
                    $conditionsArr['bind'] = array_merge($conditionsArr['bind'], array('ids' => $arr));
                }
                $conditionsArr['conditions'][] = " iCreateUserId=:iCreateUserId: ";
                $conditionsArr['bind'] = array_merge($conditionsArr['bind'], array('iCreateUserId' => $iAuthId));

                if(User::getExtraPower('dep','customer',null,true)){ //有扩展权限
                    $userIds = $this->extraPower('customer');
                    if ($userIds){
                        $conditionsArr['conditions'][] = "iCreateUserId in ({userIds:array}) ";
                        $conditionsArr['bind'] = array_merge($conditionsArr['bind'], array('userIds' => $userIds));
                    }
                }


                $parameters['conditions'] .= "AND ( ".implode(' OR ',$conditionsArr['conditions'])." )";
                $parameters['bind']        = array_merge($parameters['bind'],$conditionsArr['bind']);
            }
            //上述权限+筛选条件过滤

            $source = XhcustInfo::find($parameters)->toArray();
            foreach ($source as $index => $obj) {                //枚举处理
                $obj['iLevel'] = $enums['iLevel'][$obj['iLevel']];
                $obj['iType'] = $enums['iType'][$obj['iType']];
                $obj['bWelfare'] = $enums['bWelfare'][$obj['bWelfare']];
                $obj['bAgree'] = $enums['bAgree'][$obj['bAgree']];
                $obj['iGroupId'] = $enums['iGroupId'][$obj['iGroupId']];
                $source[$index] = $obj;
            }
            $source=array_column($source,null,'iCUId');


            $iCUIds=array_column($source,'iCUId');
            $iPlan=XHBpmPlan::find([
                'columns'=>'iBPPId,iCUId',
                'conditions'=>'bDelete=0 AND iCUId in ({ids:array})',
                'bind' => ['ids'=>$iCUIds],
                'order'=>'iCUId',
            ])->toArray();
            $iBpIds = array_values(array_filter(array_column($iPlan,'iBPPId')));
            $iPlanCIds=array_column($iPlan,'iCUId','iBPPId');
            if(count($iBpIds) > 0){
                $planC=XHBpmPlanContent::find([
                    'columns'=>'iBPCId,sNodeName,iBPPId,tRealDate',
                    'conditions'=>'bDelete=0 AND iBPPId in ({ids:array})',
                    'bind' => ['ids'=>$iBpIds],
                    'order'=>'iBPPId,iSort'
                ])->toArray();

                $node=XHBpmNode::find([
                    'columns'=>'iNodeId,sNodeName',
                    'conditions'=>'bDelete=0 AND iTPId=1',
                    'order'=>'iSort'
                ])->toArray();
                $nodes=array_column($node,'iNodeId','sNodeName');
                $nodesIdName=array_column($node,'sNodeName','iNodeId');

                $trans=XHBpmTransList::find([
                    'columns'=>'iBPPId,iStudentNum,iTeacherNum,iClassNum',
                    'conditions'=>'bDelete=0 AND iBPPId in ({ids:array})',
                    'bind' => ['ids'=>$iBpIds],
                ])->toArray();  //流转单
                $trans=array_column($trans,null,'iBPPId');
            }

            $newSocure=[];

            foreach ($iPlanCIds as $iBPPId=>$iCUId){    //处理节点字段
                foreach ($planC as $row){
                    if($iBPPId==$row['iBPPId']){
                        if(isset($trans[$row['iBPPId']])){
                            $source[$iCUId]['iStudentNum']=$trans[$row['iBPPId']]['iStudentNum'];
                            $source[$iCUId]['iTeacherNum']=$trans[$row['iBPPId']]['iTeacherNum'];
                            $source[$iCUId]['iClassNum']=$trans[$row['iBPPId']]['iClassNum'];
                        }
                        if(isset($nodes[$row['sNodeName']])){
                            if($row['tRealDate']){
                                $source[$iCUId][$nodes[$row['sNodeName']]]='是';
                            }else{
                                $source[$iCUId][$nodes[$row['sNodeName']]]='否';
                            }
                        }
                    }
                }
                $newSocure[]=$source[$iCUId];
            }


            $title = [
                'sSchoolName' =>'学校名称',
                'iType' => '类型',
                'iLevel' => '等级',
                'tSchoolDate' => '办校时间',
                'bAgree' => '协议',
                'bWelfare' => '公益',
                'iGroupId' => '组别',
                'sMarketName' => '市场负责人',
                'sOperationName' => '运营负责人',
                'sIntroName' => '介绍人姓名',
                'sChargeName' => '负责人姓名',
                'sChargePhone' => '负责人电话',
                'sProvinceName' => '所在省',
                'sCityName' => '所在市',
                'sCountyName' => '所在区',
                'sDetailedAddress' => '详细地址',
                'iStudentNum' =>'学生数',
                'iTeacherNum' =>'教师数',
                'iClassNum'   =>'班级数',
//            'tCreateDate' => '创建时间',
//            'iCreateUserId' => '创建用户',
//            'tLastModifyDate' => '最后修改时间',
//            'iLastModifyUserId' => '最后修改用户',
//            'sNodeName'        => '节点名称',
//            'finish'           => '是否完成',
            ];
            foreach ($nodesIdName as $id=>$name){
                $title[$id]=$name;
            }
            $data = [];
            foreach ($newSocure as $key => $row) {
                foreach ($title as $filed => $name) {
                    $data[$key][$filed] = isset($row[$filed]) ? $row[$filed] : '';
                }
            }
            $fileName = '客户状态列表_' . Main::getLoginUserInfo('userName');
            $this->praseLog('导出客户状态列表','导出客户状态列表');
            Tool::exportExcelOnline($fileName, $title, $data,'xlsx',['autoWidth'=>true]);
        }catch (\Exception $e){
            return $this->sendErrorResponse(500,$e->getMessage());
        }

    }


    /**
     * 用户信息批量删除
     *
     * @return string
     * created by dale 2017/6/27
     * modify by dale 20180324
     *
     */
    public function delDataAction()
    {
        if(!UserPower::checkUserPower('Cust_List_Del')){
            return $this->sendErrorResponse(400,'缺少权限');
        };
        $ids = $this->request->getPost('ids', 'string');
        if(!$ids){
            return $this->sendErrorResponse(400,'缺少参数');
        }
        try{
            $ids = explode(',', $ids);
            $objs = XhcustInfo::find([
                'conditions' => 'iCUId in ({ids:array})',
                'bind' => ['ids' => $ids]
            ]);
            $logName = Main::getLoginUserInfo('logonName');
            foreach ($objs as $obj) {
                if($obj->iSchoolId != null && $logName != 'admin' ){
                    continue;
                }else{
                    $obj->bDelete = 1;
                    if(!$obj->save()){
                        return $this->sendErrorResponse(500,'删除失败');
                    }
                }
            }
            return $this->sendSuccessResponse('删除成功');
        }catch (\Exception $e){
            return $this->sendErrorResponse(500,$e->getMessage());
        }
    }


    /**
     * 添加用户信息表单
     *
     * created by dale 2017/6/27
     */
    public function addCustomerAction()
    {
        if(!UserPower::checkUserPower('Cust_List_Add')){
            return $this->sendViewError('缺少权限');
        }
        $enums=self::getEnums();
        Assets::datetimePicker();
        Assets::select2();
        Assets::importJs('js/myMain.js');
        Assets::importJs('js/addCustomer.js');
        $this->view->setVars(array(
            'ilevel'    => XhsysEnum::getEnumByNodeName('学校等级'),
            'iGroupId'  => XhsysEnum::getEnumByNodeName('客户组别'),
            'iType'     => $enums['iType'],
            'iAidsLevel'=> $enums['iAidsLevel'],
            'iMarketIds'=>Hrm::getDepStaffByTag('xhscb'),
            'iOperateIds'=> Hrm::getDepStaffByTag('xhyyb'),
            'stage' => self::$stage
        ));
        $this->view->pick('customer/addCustomer');
    }


    /**
     * Tab标签页,客户基本信息
     *
     * created by dale 2017/6/27
     */
    public function customerTabAction()
    {//标签页
        Main::getLoginUserInfo('userId') or die('请登录');
        $iCUId = $this->request->getQuery('iCUId', 'string') or die('缺少参数iCUId');
        $this->view->pick('customer/customerTab');
        $enums=self::getEnums();
        Assets::datetimePicker();
        Assets::select2();
        Assets::importMainJs('assets/xh/xhForm.js');
        Assets::importJs('js/myMain.js');
        Assets::importJs('js/customerTab.js');
        $obj = XhcustInfo::findFirst($iCUId);
        $arr = $obj->toArray();
        $webContent = ['schoolName' => $arr['sSchoolName'], 'data' => json_encode($arr), 'iCUId' => $iCUId];
        $webContent['iType']           = $enums['iType'];
        $webContent['iAidsLevel']      = $enums['iAidsLevel'];
        $webContent['ilevel']          = XhsysEnum::getEnumByNodeName('学校等级');
        $webContent['iGroupId']        = XhsysEnum::getEnumByNodeName('客户组别');
        $webContent['iMarketIds']       = Hrm::getDepStaffByTag('xhscb');
        $webContent['iOperateIds']      = Hrm::getDepStaffByTag('xhyyb');

        $webContent['isShowEdit']      = UserPower::checkUserPower('Cust_List_Edit');
        $webContent['isShowFollow']    = UserPower::checkUserPower('Cust_List_Follow');
        $webContent['isShowIntention'] = UserPower::checkUserPower('Cust_List_Intention');
        $webContent['isShowCooperate'] = UserPower::checkUserPower('Cust_List_Cooperate');
        $webContent['isShowOperation'] = UserPower::checkUserPower('Cust_List_Operation');
        $webContent['isShowContact'] = UserPower::checkUserPower('Cust_List_Contact');
        $webContent['stage']  = self::$stage;
        $this->view->setVars($webContent);
    }

    /**
     *  检查权限
     *
     * @param $type
     * @param string $appendText
     * @return bool
     * created by dale 2017/7/27
     */
    public function checkPower($type, $appendText = "")
    {
        switch ($type) {
            case 1:
                return UserPower::checkUserPower('Cust_List_Follow' . $appendText);
            case 2:
                return UserPower::checkUserPower('Cust_List_Intention' . $appendText);
            case 3:
                return UserPower::checkUserPower('Cust_List_Cooperate' . $appendText);
            case 4:
                return UserPower::checkUserPower('Cust_List_Operation' . $appendText);
        }
        return false;
    }

    /**
     * 显示网页
     *
     * created by dale 2017/7/27
     */
    public function traceAction()
    {

        $type = $this->request->getQuery('type', 'int');
        $id = $this->request->getQuery('id', 'string');
        if(!$type || !$id){
            return $this->sendViewError('缺少参数');
        }
        if(!$this->checkPower($type)){
            return $this->sendViewError('缺少权限');
        }

        Assets::importMainJs('assets/xh/xhForm.js');
        Assets::viewer();
        Assets::datetimePicker();
        Assets::importJs('js/myMain.js');
        Assets::importJs('js/trace.js');
        $this->view->pick('customer/trace');
        $this->view->setVars(array(
            'isShowNew' => $this->checkPower($type, '_Add'),
            'showDelete' => $this->checkPower($type, '_Del'),
            'showEdit' => $this->checkPower($type, '_Edit'),
        ));
    }

    /**
     * 新建表格
     *
     * created by dale 2017/7/27
     */
    public function traceFormAction()
    {
        $type = $this->request->getQuery('type') or die('缺少参数type');
        $tid = $this->request->getQuery('tid'); //可以为空
        if ($tid == null) {
            if(!$this->checkPower($type, '_Add')){
                return $this->sendViewError('没有权限');
            }
        } else {
            if(!$this->checkPower($type, '_Edit')){
                return $this->sendViewError('没有权限');
            }
            Assets::importMainJs('assets/xh/xhForm.js');
        }
        Assets::datetimePicker();
        $this->di->get('assets')
            ->addCss('assets/fileinput/fileinput.css')
            ->addJs('customer/js/fileinput.min.js')//修改过的
            ->addJs('customer/js/zh.js');
        Assets::importJs('js/myMain.js');
        $enums = self::getEnums();
        switch ($type) {
            case 1:
                $this->view->pick('customer/followForm');
                break;
            case 2:
                $this->view->pick('customer/intentionForm');
                $this->view->setVars(array(
                    'iGrade' => $enums['iGrade'],
                    'iChargeMode' => $enums['iChargeMode'],
                    'iUsageMode' => $enums['iUsageMode'],
                    'iLevel' => $enums['iLevel'],
                    'iContent' => $enums['iContent'],
                ));
                break;
            case 4:
                $this->view->pick('customer/operationForm');
                $this->view->setVars(array(
                    'iLevel' => XhsysEnum::getEnumByNodeName('运营等级'),
                ));
                break;
        }
        if ($tid == null) {
            Assets::importJs('js/traceForm.js');
        } else {
            Assets::importJs('js/editForm.js');
        }

    }


    /**
     * 合作模式
     *
     * created by dale 2017/6/27
     */
    public function cooperationModeAction()
    {
        if(!UserPower::checkUserPower('Cust_List_Cooperate')){
            return $this->sendViewError('缺少权限');
        }
        Assets::importMainJs('assets/xh/xhForm.js');
        Assets::importJs('js/myMain.js');
        Assets::importJs('js/cooperationMode.js');
        $this->view->pick('customer/cooperationMode');
        $this->view->setVars(array(
            'isShowNew' => UserPower::checkUserPower('Cust_List_Cooperate_Add'),
            'showDelete' => UserPower::checkUserPower('Cust_List_Cooperate_Del'),
        ));
    }

    /**
     * 合作模式表格
     *
     * created by dale 2017/7/5
     */
    public function cooperationFormAction()
    {
        $tid = $this->request->getQuery('tid', 'string');
        if ($tid == null) {
            if(!UserPower::checkUserPower('Cust_List_Cooperate_Add')){
                return $this->sendErrorResponse(400,'缺少权限');
            }
        } else {
            if(!UserPower::checkUserPower('Cust_List_Cooperate_Edit')){
                return $this->sendErrorResponse(400,'缺少权限');
            }
        }
        $enums = self::getEnums();
        Assets::importMainJs('assets/xh/xhForm.js');
        Assets::importJs('js/myMain.js');
        Assets::importJs('js/cooperationForm.js');
        $this->view->pick('customer/cooperationForm');
        $this->view->setVars(array(
            'iGrade' => $enums['iGrade'],
            'iChargeMode' => $enums['iChargeMode'],
            'iUsageMode' => $enums['iUsageMode'],
            'iLevel' => $enums['iLevel'],
        ));

    }


    /**
     * 保存用户信息
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface|string
     * created by dale 2017/7/12
     */
    public function saveCustomerInfoAction()
    {
        if(!UserPower::checkUserPower('Cust_List_Add')){
            return $this->sendErrorResponse(400,'缺少权限');
        }
        $iCUId = $this->request->getPost('iCUId', 'string');
        $flag = false;
        $postName =  $this->request->getPost('sSchoolName');
        if (!$postName) {
            return $this->sendErrorResponse(400, '缺少名称');
        }
        if ($iCUId == null) {
            $obj = new XhcustInfo();
        } else {
            $obj = XhcustInfo::findFirst($iCUId);
            if ($obj->sSchoolName != $postName) {
                $flag = true;
            }
        }
        if (!$this->checkNameRepeate($postName, $iCUId)) {
            return $this->sendErrorResponse(400, '名称有重复');
        }
        $obj->assign($this->request->getPost());
        foreach (['iType','iLevel','bAgree','bWelfare','iSchoolId','iGroupId','iAidsLevel'] as $filed) {
            $obj->$filed = $obj->$filed ==''  ?  null : $obj->$filed ;
        }
//        $obj->iType = ($this->request->getPost('iType') == "" ? null : $this->request->getPost('iType'));
//        $obj->iLevel = ($this->request->getPost('iLevel') == "" ? null : $this->request->getPost('iLevel'));
//        $obj->bAgree = ($this->request->getPost('bAgree') == "" ? null : $this->request->getPost('bAgree'));
//        $obj->bWelfare = ($this->request->getPost('bWelfare') == "" ? null : $this->request->getPost('bWelfare'));
//        $obj->iSchoolId = ($this->request->getPost('iSchoolId') == "" ? null : $this->request->getPost('iSchoolId'));
//        $obj->iGroupId = ($this->request->getPost('iGroupId') == "" ? null : $this->request->getPost('iGroupId'));
//        $obj->iAidsLevel = ($this->request->getPost('iAidsLevel') == "" ? null : $this->request->getPost('iAidsLevel'));
        if (!$obj->save()) {
           return  $this->sendErrorResponse(500,'保存失败');
        }
        if ($flag) {
            if(!$obj->iSchoolId || !$postName ) {
                return $this->sendErrorResponse(500 ,'没有学校id或者学校名称为空');
            }
            $newSchool = XhschoolInfo::findFirst($obj->iSchoolId);
            $newSchool->sSchoolName = $postName;
            if (!$newSchool->save()) {
                return $this->sendErrorResponse(500 , '新库保存修改学校名称失败');
            }
//            $oldDB = new Mysql(Main::getConfigByName('oldCenterDB'));
//            if (!$oldDB) {
//                throw new \Exception('老数据中心连接失败');
//            }
//            $res = $oldDB->execute("update tblschool set schoolname='{$postName}' where schoolid = {$obj->iSchoolId}   ");
//            if (!$res) {
//                return $this->sendErrorResponse(500 , '保存失败');
//            }
            $http = new HttpClient(Main::getConfigByName('cLogin')['url']);
            $response = $http->get('refreshSchInfo?K={"V":0}');
            if (!$response->isSuccess()) {
                return $this->sendErrorResponse(500 ,'刷新失败');
            }
        }
        return $this->sendSuccessResponse('保存成功');
    }

    public function checkNameRepeate($schoolName,$iCUId=null){
        $custArr = XhcustInfo::find([
            'conditions' => 'bDelete = 0 and sSchoolName = :schoolName: ',
            'bind'        => ['schoolName' => $schoolName]
        ])->toArray();
        if (!$custArr) {
            return true;
        }
        if (count($custArr) == 1 && $iCUId == $custArr[0]['iCUId']) {
            return true;
        }
        if (count($custArr) > 1) {
            return false;
        }
        return false;
    }

    /**
     *  获取trace数据
     *
     * @return string
     *
     * created by dale 2017/7/27
     */
    public function getTraceDataAction()
    {
        $type   = $this->request->getPost('type', 'int');
        $iCUId  = $this->request->getPost('iCUId', 'string');
        if(!$type || !$iCUId){
            return $this->sendErrorResponse(400,'缺少参数');
        }
        if(!$this->checkPower($type)){
            return $this->sendErrorResponse(400,'缺少权限');
        }
        $conditions = "iCUId = :iCUId: AND iTrackType = :iTrackType: AND bDelete=0 ORDER BY tTrackTime DESC,tCreateDate DESC ";
        if ($conditions == 2) {
            $conditions = "iCUId = :iCUId: AND iTrackType = :iTrackType: AND bDelete=0 ORDER BY tCreateDate DESC ";
        }
        $parameters = array('iCUId' => $iCUId, 'iTrackType' => $type);
        $objs = XhcustTrack::find(
            array(
                $conditions,
                "bind" => $parameters,
            )
        );
        return json_encode(array(
            'showDelete' => $this->checkPower($type, '_Del'),
            'showEdit' => $this->checkPower($type, '_Edit'),
            'data' => self::pkTraceData($objs->toArray(), $type, $iCUId),
        ));
    }

    /**
     *  保存trace数据
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface|string
     * created by dale 2017/7/27
     */
    public function saveTraceDataAction()
    {
        $this->view->disable();
        $enums = self::getEnums();
        $type = $this->request->getPost('iTrackType', 'int');
        if(!$type){
            return $this->sendErrorResponse(400,'缺少参数');
        }
        $iCUTId = $this->request->getPost('iCUTId', 'string');//可以为空
        if ($iCUTId == null) {
            if(!$this->checkPower($type, '_Add')){
                return $this->sendErrorResponse(400,'缺少参数');
            }
        } else {
            if(!$this->checkPower($type, '_Edit')){
                return $this->sendErrorResponse(400,'缺少参数');
            }
        }
        if ($iCUTId == null) {
            $obj = new XhcustTrack();
        } else {
            $obj = XhcustTrack::findFirst($iCUTId);
        }
        $obj->assign($this->request->getPost());
        $sStuts = $this->request->getPost('sStatus');
        if ($type == 1) {
            $infos = XhcustTrack::find([
                'conditions' => 'bDelete=0 AND iTrackType=:iTrackType: AND iCUId=:iCUId: ',
                'bind' => array('iTrackType' => $type, 'iCUId' => $this->request->getPost('iCUId'))
            ]);
            foreach ($infos as $info) {
                if ($info->sStatus == $sStuts) {
                    return $this->sendErrorResponse(400,'不能保存相同信息的跟进情况');
                }
            }
        }
        $result = $obj->save();
        if ($result) {
            foreach ($enums['iContent'] as $icontent => $text) {
                $contentData = $this->request->getPost('tTime-' . $icontent, 'string');
                if ($contentData) {
                    $this->saveContent($icontent, $contentData, $obj->iCUId, $obj->iCUTId);
                }
            }
            return $this->sendSuccessResponse('保存成功');
        } else {
            return $this->sendErrorResponse(500,'保存失败');
        }
    }

    /**
     * 保存content
     *
     * @param $icontent
     * @param $date
     * @param $iCUId
     * @param $iCUTId
     * created by dale 2017/8/10
     */
    public function saveContent($icontent, $date, $iCUId, $iCUTId)
    {
        $obj = XhcustContent::findFirst([
            'conditions' => "bDelete=:bDelete: AND iContent=:iContent: AND iCUTId=:iCUTId: ",
            'bind' => array('iContent' => $icontent, 'bDelete' => 0, 'iCUTId' => $iCUTId),
        ]) or $obj = new XhcustContent();
        $obj->iContent = $icontent;
        $obj->tTime = $date;
        $obj->iCUId = $iCUId;
        $obj->iCUTId = $iCUTId;
        $obj->save();
        $this->praseLog('保存跟进详情成功','保存跟进详情成功');
    }


    /**
     * 获取合作模式数据
     *
     * @return string list json
     * created by dale 2017/6/27 下午5:02
     */
    public function getCooperationModeAction()
    {
        if(!UserPower::checkUserPower('Cust_List_Cooperate')){
            return $this->sendErrorResponse(400,'缺少权限');
        }
        $enums = self::getEnums();//获取枚举
        $iCUId = $this->request->getPost('iCUId', 'string');
        $conditions = "iCUId = :iCUId: AND iTrackType = :iTrackType: AND bDelete=0 ORDER BY tCreateDate  ";

        $parameters = array('iCUId' => $iCUId, 'iTrackType' => 3);
        $objs = XhcustTrack::find(
            array(
                $conditions,
                "bind" => $parameters,
            )
        );
        $traceArray = $objs->toArray();
        foreach ($traceArray as $index => $trace) {
            $trace['sGrade'] = $enums['iGrade'][$trace['iGrade']];
            $trace['sChargeMode'] = $enums['iChargeMode'][$trace['iChargeMode']];
            $trace['sUsageMode'] = $enums['iUsageMode'][$trace['iUsageMode']];
            $trace['sLevel'] = $enums['iLevel'][$trace['iLevel']];
            $traceArray[$index] = $trace;
        }
        return json_encode(array(
            'showDelete' => UserPower::checkUserPower('Cust_List_Cooperate_Del'),
            'showEdit' => UserPower::checkUserPower('Cust_List_Cooperate_Edit'),
            'data' => $traceArray
        ));
    }

    /**
     *保存合作模式
     *
     * @return string list or one json
     * created by dale 2017/6/27 下午5:03
     */
    public function saveCooperationModeAction()
    {
        $this->view->disable();
        $iCUTId = $this->request->getPost('iCUTId', 'string');
        if ($iCUTId == null) {
            if(!UserPower::checkUserPower('Cust_List_Cooperate_Add')){
                return $this->sendErrorResponse(400,'缺少权限');
            };
            $obj = new XhcustTrack();
        } else {
            if(!UserPower::checkUserPower('Cust_List_Cooperate_Edit')){
                return $this->sendErrorResponse(400,'缺少权限');
            };
            $obj = XhcustTrack::findFirst($iCUTId);
        }
        $obj->assign($this->request->getPost());
        $obj->iTrackType = 3;
        $result = $obj->save();
        if ($result) {
            if ($iCUTId != null) {
                $array = $obj->toArray();
                return $this->sendJsonResponse($array);
            } else {
                $this->dispatcher->forward(array(
                    "controller" => "customer",
                    "action" => "getCooperationMode",
                ));
            }
        } else {
            return $this->sendErrorResponse(400,'保存失败');
        }
    }


    /**
     *用于编辑 查找记录
     *
     * @return string  一条记录
     *
     * created by dale 2017/6/27
     */
    public function findTraceDataAction()
    {
        $this->view->disable();
        //$enums=self::getEnums();
        $iCUTId = $this->request->getPost('iCUTId', 'string');
        if(!$iCUTId){
            return $this->sendErrorResponse(400,'缺少参数');
        }
        $parameters = array(
            'conditions' => "iCUTId=:iCUTId: And bDelete=0",
            'bind' => array('iCUTId' => $iCUTId),
        );
        $obj = XhcustTrack::findFirst($parameters);
        $data = $obj->toArray();

        if ($obj->iTrackType == 2) {
            $objs = XhcustContent::find([
                'conditions' => "bDelete=:bDelete: AND iCUTId=:iCUTId: ",
                'bind' => array('bDelete' => 0, 'iCUTId' => $data['iCUTId']),
            ]);
            if (!$objs) {
                return $this->sendJsonResponse($data);
            } else {
                foreach ($objs->toArray() as $ob) {
                    $data['tTime-' . $ob['iContent']] = $ob['tTime'];
                }
                return $this->sendJsonResponse($data);
            }
        } else {
            return $this->sendJsonResponse($data);
        }

    }

    /**
     * 用于删除记录
     * created by dale 2017/6/27 下午4:56
     * modified by dale 2017/6/27 下午8:12
     */
    public function deleteTraceDataAction()
    {

        $this->view->disable();
        $iCUTId = $this->request->getPost('iCUTId', 'string');
        $type = $this->request->getPost('type', 'int');
        $iCUId = $this->request->getPost('iCUId', 'string');
        if(!$iCUTId || !$type || !$iCUId){
            return $this->sendErrorResponse(400,'缺少参数');
        }
        if(!$this->checkPower($type, '_Del')){
            return $this->sendErrorResponse(400,'缺少权限');
        }
        $parameters = array(
            'conditions' => "iCUTId=:iCUTId: And bDelete=0",
            'bind' => array('iCUTId' => $iCUTId),
        );
        $obj = XhcustTrack::findFirst($parameters);
        $obj->bDelete = 1;
        $result = $obj->save();
        if ($result) {
            if ($type == 3) {
                $this->dispatcher->forward(array(
                    "controller" => "customer",
                    "action" => "getCooperationMode",
                    "params" => ['iCUId' => $iCUId],
                ));
            } else {
                //getTraceData
                $this->dispatcher->forward(array(
                    "controller" => "customer",
                    "action" => "getTraceData",
                    "params" => ['iCUId' => $iCUId, 'type' => $type],
                ));
            }
        } else {
           return $this->sendErrorResponse('删除失败');
        }
    }




    public function getAreaDataAction()
    {
        $this->view->disable();
        $iAreaCode = $this->request->getQuery('pid', 'string');  //从0开始
        if ($iAreaCode == null) {
            die('缺少参数');
        }

        $jsonArray=\Admin\Models\overt\XhovertAreainfo::getChildArea($iAreaCode);
        $array=[];
        foreach ($jsonArray as $value){
            $item = Array(
                'id' => $value['areaCode'],
                'text' => $value['areaName'],
            );
            array_push($array, $item);
        }

        return $this->sendJsonResponse($array);
    }


    public function getAreaBynamesAction($names=null)
    {
        $this->view->disable();
        if(!isset($names)){
            $names = $this->request->getPost('qnames', 'string') or die('缺少参数');
        }
        $objs = XhovertAreainfo::find([
            'conditions' => 'areaName in ({names:array})',
            'bind' => ['names' => $names]
        ]);


        
        if (!$objs->toArray()) {
            return json_encode([]);
        }
        $items = [];
        foreach ($objs as $obj) {
            $item = Array(
                'id' => $obj->areaCode,
                'text' => $obj->areaName,
            );
            array_push($items, $item);
        }
        return json_encode($items);
    }




    /**
     *封装trace数据以json串返回
     *
     * @param $traceArray
     * @param $type
     * @return string
     *
     */
    public static function pkTraceData($traceArray, $type, $iCUId = null)
    {

        $enums = self::getEnums();
        $enum2 = ['iLevel' => XhsysEnum::getEnumByNodeName('运营等级')];
        $ImgPath = Main::getConfigByName('customer')['downUrl'];
        $filePath = Main::getConfigByName('customer')['downUrl'];
        $newArray = array();
        Main::runUserNameById($traceArray, 'iLastModifyUserId', true);
        Main::runUserNameById($traceArray, 'iCreateUserId', true);
        $contentArray = self::getContentArray($iCUId);
        foreach ($traceArray as $trace) {
            $item = array(
                'id' => $trace['iCUTId'],
                'content' => str_replace(array("\r\n", "\r", "\n"),'<br>',$trace['sStatus']),
                'imgPath' => $ImgPath,
                'filePath' => $filePath,
                'images' => $trace['sImages'],
                'files' => $trace['sFiles'],
                'footer' => array(
                    'left' => '修改时间:' . $trace['tLastModifyDate'] . '&nbsp;&nbsp;修改人:' . $trace['iLastModifyUserId'],
                    'right' => '创建时间:' . $trace['tCreateDate'] . '&nbsp;&nbsp;创建人:' . $trace['iCreateUserId'],
                ),
                'time' => $trace['tTrackTime']
            );
            if ($type == 1) {
                $trace['tTrackTime'] = date('Y-m-d', strtotime($trace['tTrackTime']));
                $item['title'] = '<b>跟踪时间:</b>&nbsp;&nbsp;' . $trace['tTrackTime'];
                $item['time'] = $trace['tTrackTime'];
            } else if ($type == 4) {
                $trace['tTrackTime'] = date('Y-m-d', strtotime($trace['tTrackTime']));
                $item['title'] = '<b>时间:</b>&nbsp;&nbsp;' . $trace['tTrackTime'] . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<b>等级:</b>:&nbsp;&nbsp;' . $enum2['iLevel'][$trace['iLevel']];
                $item['time'] = $trace['tTrackTime'];
            } else if ($type == 2) {
                $item['title'] = '<b>年份:</b>&nbsp;&nbsp;' . $trace['sYear'] . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'
                    . '<b>意向年级:</b>&nbsp;&nbsp;' . $enums['iGrade'][$trace['iGrade']] . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<b>意向等级:</b>&nbsp;&nbsp;' .
                    $enums['iLevel'][$trace['iLevel']] . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<b>收费模式:</b>&nbsp;&nbsp;' .
                    $enums['iChargeMode'][$trace['iChargeMode']] . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<b>使用模式:</b>&nbsp;&nbsp;' . $enums['iUsageMode'][$trace['iUsageMode']];
                $item['retain'] = '';

                if ($tTime = $contentArray[$trace['iCUTId']]) {

                    foreach ($enums['iContent'] as $id => $text) {
                        if ($tTime['tTime-' . $id]) {
                            $item['retain'] .= '<b>' . $text . '时间:</b>&nbsp;&nbsp;' . $tTime['tTime-' . $id] . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
                        }
                    }
                }

                $item['time'] = $trace['tCreateDate'];
            }
            array_push($newArray, $item);
        }

        return $newArray;
    }

    /**
     * 获取content数据
     *
     * @param $iCUId
     * @return array
     * created by dale 2017/8/10
     */
    public static function getContentArray($iCUId = 1)
    {
        $objs = XhcustContent::find([
            'conditions' => "bDelete=:bDelete: AND iCUId=:iCUId: ",
            'bind' => array('bDelete' => 0, 'iCUId' => $iCUId),
            'order' => 'iCUTId'
        ]);
        if (!$objs) {
            return [];
        } else {
            $content = $objs->toArray();
            $array = [];
            foreach ($content as $ob) {
                $array[$ob['iCUTId']]['tTime-' . $ob['iContent']] = $ob['tTime'];
            }
            return $array;
        }
    }

    /**
     * 封装trace数据以json串返回
     *
     * @param $array
     * @param $type
     * @return string
     *
     * created by dale 2017/7/12 上午10:28
     */
    public static function pkOneTraceData($array, $type, $iCUId = null)
    {

        $ImgPath = Main::getConfigByName('customer')['downUrl'];
        $filePath = Main::getConfigByName('customer')['downUrl'];
        $enums = self::getEnums();
        $enum2 = ['iLevel' => XhsysEnum::getEnumByNodeName('运营等级')];
        $contentArray = self::getContentArray($iCUId);
        $item = array(
            'id' => $array['iCUTId'],
            'content' => str_replace(array("\r\n", "\r", "\n"),'<br>',$array['sStatus']),
            'footer' => array(
                'left' => '修改时间:' . $array['tLastModifyDate'] . '&nbsp;&nbsp;修改人:' . XhsysUser::findFirst($array['iLastModifyUserId'])->toArray()['sUserName'],
                'right' => '创建时间:' . $array['tCreateDate'] . '&nbsp;&nbsp;创建人:' . XhsysUser::findFirst($array['iCreateUserId'])->toArray()['sUserName'],
            ),
            'images' => $array['sImages'],
            'files' => $array['sFiles'],
            'imgPath' => $ImgPath,
            'filePath' => $filePath,
        );
        if ($type == 1) {
            $item['title'] = '跟踪时间:' . $array['tTrackTime'];
            $item['time'] = $array['tTrackTime'];
        } else if ($type == 4) {

            $item['title'] = '时间:&nbsp;&nbsp;' . $array['tTrackTime'] . '&nbsp;&nbsp;&nbsp;&nbsp;等级:&nbsp;&nbsp;' . $enum2['iLevel'][$array['iLevel']];
            $item['time'] = $array['tTrackTime'];
        } else if ($type == 2) {
            $item['title'] = '年份:&nbsp;&nbsp;' . $array['sYear'] . '&nbsp;&nbsp;&nbsp;&nbsp;'
                . '意向年级:&nbsp;&nbsp;' . $enums['iGrade'][$array['iGrade']] . '&nbsp;&nbsp;&nbsp;&nbsp;意向等级:&nbsp;&nbsp;' .
                $enums['iLevel'][$array['iLevel']] . '&nbsp;&nbsp;&nbsp;&nbsp;收费模式:' .
                $enums['iChargeMode'][$array['iChargeMode']] . '&nbsp;&nbsp;&nbsp;&nbsp;使用模式:' .
                $enums['iUsageMode'][$array['iUsageMode']];

            $item['retain'] = '';
            if ($tTime = $contentArray[$array['iCUTId']]) {
                if ($tTime['tTime-1']) {
                    $item['retain'] .= '<b>开家长会时间:</b>&nbsp;&nbsp;' . $tTime['tTime-1'] . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
                }
                if ($tTime['tTime-2']) {
                    $item['retain'] .= '<b>教师培训时间:</b>&nbsp;&nbsp;' . $tTime['tTime-2'] . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
                }
                if ($tTime['tTime-3']) {
                    $item['retain'] .= '<b>网络改造时间:</b>&nbsp;&nbsp;' . $tTime['tTime-3'] . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
                }
            }

            $item['time'] = $array['tCreateDate'];
        }
        return $item;
    }


    /**
     *文件上传
     *
     * @return string
     * created by dale 2017/7/5 上午9:39
     */
    public function ajaxTestAction()
    {
        $this->view->disable();
        $iCUId = $this->request->getQuery('id', 'string');
        if(!$iCUId){
            return $this->sendErrorResponse(400,'缺少参数');
        }
        if(!$this->request->hasFiles()){
            return $this->sendErrorResponse(400,'没有文件上传');
        }

        $file = $this->request->getUploadedFiles()[0];
        $savePath = Main::getConfigByName('customer')['savePath'];

        if (!is_dir($savePath)) {
            mkdir($savePath, 0777, true) or die($savePath . '创建失败');
        }
        $root = realpath($savePath);
        substr($root, strlen($root) - 1, strlen($root)) == '/' or $root .= '/';

        $extension = strtolower($file->getExtension());

        if ($extension == 'jpg' || $extension == 'png' || $extension == 'gif' || $extension == 'jpeg') {
            $subDirName = '/img/';
        } else {
            $subDirName = '/file/';
        }
        $dirPath = $root . $iCUId . $subDirName;
        if (!is_dir($dirPath)) {
            mkdir($dirPath, 0777, true) or die($dirPath . '创建失败');
        }
        $url = $iCUId . $subDirName . md5_file($file->getTempName()) . '.' . $file->getExtension();
        $filePath = $dirPath . md5_file($file->getTempName()) . '.' . $file->getExtension();

        $name = $file->getName();
        $file->moveTo($filePath);

        return $this->sendJsonResponse(['url' => $url, 'fileName' => $name]);
    }

    /**
     * 删除图片,更新数据库中记录,删除服务器上的文件
     * @param $fileType
     * created by dale 2017/6/30 下午3:23
     * modify by dale 20180508  添加文件删除
     */
    public function ajaxDeleteAction($fileType=null)
    {
        $this->view->disable();
        $iCUTId = $this->request->getPost('iCUTId', 'string');
        $rmId = $this->request->getPost('rmId', 'int');
        $type = $this->request->getPost('type', 'int');
        if ($rmId == null || !$iCUTId || !$type) {
            return $this->sendErrorResponse('缺少参数');
        }
        $obj = XhcustTrack::findFirst($iCUTId);

        $image = $obj->toArray();
        if($fileType == 'fileDelete'){
            $images = explode(',', $image['sFiles']);
            $url = '';
            foreach ($images as $key => $value) {
                if ($key != $rmId && $value != '') {
                    $url = $url . $value . ',';
                }
            }
            $obj->sFiles = $url;
        }else{
            $images = explode(',', $image['sImages']);
            $url = '';
            foreach ($images as $key => $value) {
                if ($key != $rmId && $value != '') {
                    $url = $url . $value . ',';
                }
            }
            $obj->sImages = $url;
        }
        $result = $obj->save();
        $showDelete = $this->checkPower($type, '_Del');
        if ($result) {
            $obj = XhcustTrack::findFirst($iCUTId);
            $array = $obj->toArray();
            $this->praseLog('文件删除成功','文件删除成功');
            return json_encode(array(
                'showDelete' => $showDelete,
                'data' => self::pkOneTraceData($array, $type, $array['iCUId']),
            ));
        }
        $this->praseLog('文件删除失败','文件删除失败');
        return false;
    }




    /**
     * 跟进详情
     *
     * created by dale 2017/8/9
     */
    public function followDetailAction()
    {
        $this->view->pick('customer/followDetail');
        Assets::importJs('js/followDetail.js');
        Assets::easyUI();
        Template::exists('followDetail', 'list') or die(Main::showMessageModal('配置文件不存在，请先创建！', 109106002));//检查public/template/from/目录下是否都存在template文件夹
        $listSearchArr = array();
        $listSearchArr[] = array('type' => 'text', 'id' => 'List_Search_StartTime', 'label' => ' 开始时间： ');
        $listSearchArr[] = array('type' => 'text', 'id' => 'List_Search_EndTime', 'label' => ' 结束时间： ');
        $listSearchArr[] = array('type' => 'text', 'id' => 'list_search', 'label' => ' 搜索： ');
        $listSearchArr[] = array('type' => 'button', 'id' => 'bt_list_search', 'text' => '查找', 'icon' => 'fa-search', 'style' => 'margin-left:10px');
        $listSearchArr[] = array('type' => 'button', 'id' => 'excel_export', 'text' => '导出excel', 'icon' => 'fa fa-file-excel-o');
        $this->view->setVars(array(
            'List' => Template::createList('List', 'followDetail', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, true),
                'checkbox' => false,
            ]),

        ));
    }

    /**
     *  获取跟进详情信息,搜索未添加
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * created by dale 2017/8/9
     */
    public function getFollowDeDataAction()
    {

        $key = $this->request->getPost('key', 'string');
        $startTime = $this->request->getPost('startTime', 'string');
        $endTime = $this->request->getPost('endTime', 'string');
        try{
            $builder = $this->modelsManager->createBuilder()
                ->columns('t.iCUTId,t.tTrackTime,t.iCreateUserId,t.iCUId,t.sStatus,t.tLastModifyDate,t.iLastModifyUserId,p.sSchoolName,u.sUserName')
                ->addFrom('Admin\Models\crm\XhcustTrack', 't')
                ->leftJoin('Admin\Models\crm\XhcustInfo', 't.iCUId=p.iCUId', 'p')
                ->leftJoin('Admin\Models\user\XhsysUser', 't.iCreateUserId=u.iUserId', 'u')
                ->where('t.bDelete=0 AND t.iTrackType=1')
                ->orderBy('t.iCreateUserId,t.tTrackTime DESC');


            if ($key) {
                $builder->andWhere('p.sSchoolName LIKE :key: OR u.sUserName LIKE :key:', array('key' => '%' . $key . '%'));
            }

            if ($startTime && $endTime) {
                $builder->andWhere("t.tTrackTime >=:startTime:", array('startTime' => $startTime))
                    ->andWhere('t.tTrackTime <=:endTime:', array('endTime' => $endTime));
            }


            if(!User::isAdmin()){
                $iAuthId = Main::getLoginUserInfo('userId');
                $conditionArr = [
                    'conditions' => [],
                    'bind'       => []
                ];
                $conditionArr['conditions'][] = ' t.iCreateUserId = :iCreateUserId:  ';
                $conditionArr['bind']       = array_merge($conditionArr['bind'],['iCreateUserId'=>$iAuthId]);

                if(User::getExtraPower('dep','customerFollow',null,true)){ //没有扩展权限
                    $userIds = $this->extraPower('customerFollow');
                    if ($userIds) {
                        $conditionArr['conditions'][] = ' t.iCreateUserId  in ({userIds:array})   ';
                        $conditionArr['bind']       = array_merge($conditionArr['bind'],['userIds' => $userIds]);
                    }
//                    $builder->andWhere('( t.iCreateUserId  in ({userIds:array}) OR t.iCreateUserId = :iCreateUserId:  )',['userIds' => $userIds,'iCreateUserId' => $iAuthId]);

                }
                $auth = XhcustAuth::find([
                    'conditions' => 'bDelete=0 AND iAuthId=:iAuthId:',
                    'bind' => array('iAuthId' => $iAuthId)
                ]);
                if (count($auth->toArray())>0) {
                    $arr = array_column($auth->toArray(),'iCUId');
                    $conditionArr['conditions'][] = ' t.iCUId in ({ids:array})   ';
                    $conditionArr['bind']       = array_merge($conditionArr['bind'],['ids' => $arr]);
                }

                $builder->andWhere(implode(' OR ',$conditionArr['conditions']) ,$conditionArr['bind']);


            }
            $data = Main::runBuilderPaginator($builder, true);
            foreach ($data['rows'] as $key => $row) {
                $row['tTrackTime'] = date('Y-m-d', strtotime($row['tTrackTime']));
                $data['rows'][$key] = $row;
            }

            Main::runUserNameById($data['rows'], 'iLastModifyUserId', true);
            return $this->sendJsonResponse($data);

        }catch (\Exception $e){
            return $this->sendErrorResponse(500,$e->getMessage());
        }


    }


    /**
     * 导出跟进详情
     * created by dale 2017/8/10
     */
    public function exportFollowDetailAction()
    {
        $this->view->disable();
        $startTime = $this->request->getQuery('startTime', 'string');
        $endTime = $this->request->getQuery('endTime', 'string');
        $key = $this->request->getQuery('key', 'string');
        $builder = $this->modelsManager->createBuilder()
            ->columns('t.iCUTId,t.tTrackTime,t.iCreateUserId,t.iCUId,t.sStatus,t.tLastModifyDate,t.iLastModifyUserId,p.sSchoolName,u.sUserName')
            ->addFrom('Admin\Models\crm\XhcustTrack', 't')
            ->leftJoin('Admin\Models\crm\XhcustInfo', 't.iCUId=p.iCUId', 'p')
            ->leftJoin('Admin\Models\user\XhsysUser', 't.iCreateUserId=u.iUserId', 'u')
            ->where('t.bDelete=0 AND t.iTrackType=1')
            ->orderBy('t.iCreateUserId');
        if ($startTime && $endTime) {
            $builder->andWhere("t.tTrackTime >=:startTime:", array('startTime' => $startTime))
                ->andWhere('t.tTrackTime <=:endTime:', array('endTime' => $endTime));
        }
        if ($key) {
            $builder->andWhere('p.sSchoolName LIKE :key: OR u.sUserName LIKE :key:', array('key' => '%' . $key . '%'));
        }

        if(!User::isAdmin()){
            $iAuthId = Main::getLoginUserInfo('userId');
            $conditionArr = [
                'conditions' => [],
                'bind'       => []
            ];
            $conditionArr['conditions'][] = ' t.iCreateUserId = :iCreateUserId:  ';
            $conditionArr['bind']       = array_merge($conditionArr['bind'],['iCreateUserId'=>$iAuthId]);

            if(User::getExtraPower('dep','customerFollow',null,true)){ //没有扩展权限
                $userIds = $this->extraPower('customerFollow');
                if ($userIds) {
                    $conditionArr['conditions'][] = ' t.iCreateUserId  in ({userIds:array})   ';
                    $conditionArr['bind']       = array_merge($conditionArr['bind'],['userIds' => $userIds]);
                }
//                    $builder->andWhere('( t.iCreateUserId  in ({userIds:array}) OR t.iCreateUserId = :iCreateUserId:  )',['userIds' => $userIds,'iCreateUserId' => $iAuthId]);
            }
            $auth = XhcustAuth::find([
                'conditions' => 'bDelete=0 AND iAuthId=:iAuthId:',
                'bind' => array('iAuthId' => $iAuthId)
            ]);
            if (count($auth->toArray())>0) {
                $arr = array_column($auth->toArray(),'iCUId');
                $conditionArr['conditions'][] = ' t.iCUId in ({ids:array})   ';
                $conditionArr['bind']       = array_merge($conditionArr['bind'],['ids' => $arr]);
            }

            $builder->andWhere(implode(' OR ',$conditionArr['conditions']) ,$conditionArr['bind']);
        }


        $source = $builder->getQuery()->execute()->toArray();
        Main::runUserNameById($source, 'iLastModifyUserId', true);

        foreach ($source as $key => $row) {
            $row['tTrackTime'] = date('Y-m-d', strtotime($row['tTrackTime']));
            $source[$key] = $row;
        }

        $title = [
            'sUserName' => '名称',
            'tTrackTime' => '跟进时间',
            'sSchoolName' => '学校',
            'sStatus' => '内容',
            'tLastModifyDate' => '最后修改时间',
            'iLastModifyUserId' => '最后修改用户',
        ];
        $data = [];
        foreach ($source as $key => $row) {
            foreach ($title as $filed => $name) {
                $data[$key][$filed] = isset($row[$filed]) ? $row[$filed] : '';
            }
        }
        $fileName = '跟进详情_' . $startTime . '_' . $endTime;
        $this->praseLog('导出跟进详情','导出跟进详情');
        Tool::exportExcelOnline($fileName, $title, $data);
    }


    /**
     * 意向日程
     *
     * created by dale 2017/8/9
     */
    public function intentRouteAction()
    {
        $enums = self::getEnums();
        $this->view->pick('customer/intentRoute');
        Assets::importJs('js/intentRoute.js');
        Assets::easyUI();
        Template::exists('intentRoute', 'list') or die(Main::showMessageModal('配置文件不存在，请先创建！', 109106002));//检查public/template/from/目录下是否都存在template文件夹
        $listSearchArr = array();
        $enums['iContent'][''] = '--内容--';

        $listSearchArr[] = array('type' => 'text', 'id' => 'List_Search_StartTime', 'label' => ' 开始时间： ');
        $listSearchArr[] = array('type' => 'text', 'id' => 'List_Search_EndTime', 'label' => ' 结束时间： ');
        $listSearchArr[] = array('type' => 'select', 'id' => 'select_content', 'data' => $enums['iContent'], 'default' => '');
        $listSearchArr[] = array('type' => 'text', 'id' => 'list_search', 'label' => ' 搜索： ');
        $listSearchArr[] = array('type' => 'button', 'id' => 'bt_list_search', 'text' => '查找', 'icon' => 'fa-search', 'style' => 'margin-left:10px');
        $listSearchArr[] = array('type' => 'button', 'id' => 'excel_export', 'text' => '导出excel', 'icon' => 'fa fa-file-excel-o');
       // var_dump(Template::createSearchToolBar($listSearchArr, false));die();
        $this->view->setVars(array(
            'List' => Template::createList('List', 'intentRoute', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, false),
                'checkbox' => false,
            ]),
        ));
    }

    /**
     * 获取意向日程
     *
     * created by dale 2017/8/9
     */
    public function getIntentRouteAction()
    {

        $key = $this->request->getPost('key', 'string');
        $startTime = $this->request->getPost('startTime', 'string');
        $endTime = $this->request->getPost('endTime', 'string');
        $iContent = $this->request->getPost('content', 'string');

        $enums = self::getEnums();

        $builder = $this->modelsManager->createBuilder()
            ->columns('c.iCUTId,c.iCUId,c.iCURId,c.iContent,c.tTime,c.iCreateUserId,c.tCreateDate,c.tLastModifyDate,c.iLastModifyUserId,i.sSchoolName,t.sYear,t.iGrade,t.iChargeMode,t.iUsageMode,t.iLevel')
            ->addFrom('Admin\Models\crm\XhcustContent', 'c')
            ->leftJoin('Admin\Models\crm\XhcustInfo', 'i.iCUId=c.iCUId', 'i')
            ->leftJoin('Admin\Models\crm\XhcustTrack', 't.iCUTId=c.iCUTId', 't')
            ->where('t.bDelete=0')
            ->orderBy('c.tTime');

        if ($key) {
            $builder->andWhere('i.sSchoolName LIKE :key: ', array('key' => '%' . $key . '%'));
        }
        if ($startTime && $endTime) {
            $builder->andWhere("c.tTime >=:startTime:", array('startTime' => $startTime))
                ->andWhere('c.tTime <=:endTime:', array('endTime' => $endTime));
        }
        if ($iContent) {
            $builder->andWhere("c.iContent =:iContent:", array('iContent' => $iContent));
        }

        if(!User::isAdmin()){

            $iAuthId = Main::getLoginUserInfo('userId');
            $conditionArr = [
                'conditions' => [],
                'bind'       => []
            ];

            $conditionArr['conditions'][] = ' c.iCreateUserId = :iCreateUserId:  ';
            $conditionArr['bind']       = array_merge($conditionArr['bind'],['iCreateUserId'=>$iAuthId]);

            if(User::getExtraPower('dep','customerIntention',null,true)){
                $userIds = $this->extraPower('customerIntention');
                $conditionArr['conditions'][] = ' c.iCreateUserId  in ({userIds:array})   ';
                $conditionArr['bind']       = array_merge($conditionArr['bind'],['userIds' => $userIds]);
            }
            $auth = XhcustAuth::find([
                'conditions' => 'bDelete=0 AND iAuthId=:iAuthId:',
                'bind' => array('iAuthId' => $iAuthId)
            ]);
            if (count($auth->toArray())>0) {
                $arr = array_column($auth->toArray(),'iCUId');
                $conditionArr['conditions'][] = ' c.iCUId in ({ids:array})   ';
                $conditionArr['bind']       = array_merge($conditionArr['bind'],['ids' => $arr]);
            }

            $builder->andWhere(implode(' OR ',$conditionArr['conditions']) ,$conditionArr['bind']);
        }




        $data = Main::runBuilderPaginator($builder, true);

        $weekarray = array(0 => "日", 1 => "一", 2 => "二", 3 => "三", 4 => "四", 5 => "五", 6 => "六");

        foreach ($data['rows'] as $index => $value) {
            $value['tTime'] = $value['tTime'] . "(星期" . $weekarray[date("w", strtotime($value['tTime']))] . ')';
            $value['iContent'] = $enums['iContent'][$value['iContent']];
            $value['iGrade'] = $enums['iGrade'][$value['iGrade']];
            $value['iLevel'] = $enums['iLevel'][$value['iLevel']];
            $value['iChargeMode'] = $enums['iChargeMode'][$value['iChargeMode']];
            $value['iUsageMode'] = $enums['iUsageMode'][$value['iUsageMode']];
            $data['rows'][$index] = $value;
        }
        Main::runUserNameById($data['rows'], 'iCreateUserId', true);
        Main::runUserNameById($data['rows'], 'iLastModifyUserId', true);
        return $this->response->setContent(json_encode($data, JSON_UNESCAPED_UNICODE));

    }


    /**
     * 导出意向日程
     * created by dale 2017/8/10
     */
    public function exportIntentRouteAction()
    {
        $this->view->disable();
        $key = $this->request->getQuery('key', 'string');
        $startTime = $this->request->getQuery('startTime', 'string');
        $endTime = $this->request->getQuery('endTime', 'string');
        $iContent = $this->request->getQuery('content', 'string');


        $enums = self::getEnums();

        $builder = $this->modelsManager->createBuilder()
            ->columns('c.iCUTId,c.iCUId,c.iCURId,c.iContent,c.tTime,c.iCreateUserId,c.tCreateDate,c.tLastModifyDate,c.iLastModifyUserId,i.sSchoolName,t.sYear,t.iGrade,t.iChargeMode,t.iUsageMode,t.iLevel')
            ->addFrom('Admin\Models\crm\XhcustContent', 'c')
            ->leftJoin('Admin\Models\crm\XhcustInfo', 'i.iCUId=c.iCUId', 'i')
            ->leftJoin('Admin\Models\crm\XhcustTrack', 't.iCUTId=c.iCUTId', 't')
            ->where('t.bDelete=0')
            ->orderBy('c.tTime');

        if ($key) {
            $builder->andWhere('i.sSchoolName LIKE :key: ', array('key' => '%' . $key . '%'));
        }

        if ($startTime && $endTime) {
            $builder->andWhere("c.tTime >=:startTime:", array('startTime' => $startTime))
                ->andWhere('c.tTime <=:endTime:', array('endTime' => $endTime));
        }

        if ($iContent) {
            $builder->andWhere("c.iContent =:iContent:", array('iContent' => $iContent));
        }

        if(!User::isAdmin()){
            $iAuthId = Main::getLoginUserInfo('userId');
            $conditionArr = [
                'conditions' => [],
                'bind'       => []
            ];

            $conditionArr['conditions'][] = ' c.iCreateUserId = :iCreateUserId:  ';
            $conditionArr['bind']       = array_merge($conditionArr['bind'],['iCreateUserId'=>$iAuthId]);

            if(User::getExtraPower('dep','customerIntention',null,true)){
                $userIds = $this->extraPower('customerIntention');
                $conditionArr['conditions'][] = ' c.iCreateUserId  in ({userIds:array})   ';
                $conditionArr['bind']       = array_merge($conditionArr['bind'],['userIds' => $userIds]);
            }
            $auth = XhcustAuth::find([
                'conditions' => 'bDelete=0 AND iAuthId=:iAuthId:',
                'bind' => array('iAuthId' => $iAuthId)
            ]);
            if (count($auth->toArray())>0) {
                $arr = array_column($auth->toArray(),'iCUId');
                $conditionArr['conditions'][] = ' c.iCUId in ({ids:array})   ';
                $conditionArr['bind']       = array_merge($conditionArr['bind'],['ids' => $arr]);
            }

            $builder->andWhere(implode(' OR ',$conditionArr['conditions']) ,$conditionArr['bind']);
        }

        $source = $builder->getQuery()->execute()->toArray();

        $weekarray = array(0 => "日", 1 => "一", 2 => "二", 3 => "三", 4 => "四", 5 => "五", 6 => "六");

        foreach ($source as $index => $value) {
            $value['tTime'] = $value['tTime'] . "(星期" . $weekarray[date("w", strtotime($value['tTime']))] . ')';
            $value['iContent'] = $enums['iContent'][$value['iContent']];
            $value['iGrade'] = $enums['iGrade'][$value['iGrade']];
            $value['iLevel'] = $enums['iLevel'][$value['iLevel']];
            $value['iChargeMode'] = $enums['iChargeMode'][$value['iChargeMode']];
            $value['iUsageMode'] = $enums['iUsageMode'][$value['iUsageMode']];
            $source[$index] = $value;
        }
        Main::runUserNameById($source, 'iCreateUserId', true);
        Main::runUserNameById($source, 'iLastModifyUserId', true);


        $title = [
            'tTime' => '时间',
            'sSchoolName' => '学校',
            'iContent' => '内容',
            'sYear' => '入学年份',
            'iGrade' => '年级',
            'iChargeMode' => '收费模式',
            'iUsageMode' => '使用模式',
            'iLevel' => '意向等级',
            'tCreateDate' => '创建时间',
            'iCreateUserId' => '创建用户',
            'tLastModifyDate' => '最后修改时间',
            'iLastModifyUserId' => '最后修改用户',
        ];
        $data = [];
        foreach ($source as $key => $row) {
            foreach ($title as $filed => $name) {
                $data[$key][$filed] = isset($row[$filed]) ? $row[$filed] : '';
            }
        }
        $fileName = '跟进日程_' . $startTime . '_' . $endTime;
        $this->praseLog('导出意向日程','导出意向日程');
        Tool::exportExcelOnline($fileName, $title, $data);
    }

    /**
     * 权限管理
     * created by dale 2017/8/11
     */
    public function authManageAction()
    {
        $iCUId = $this->request->getQuery('id', 'string');
        $iCUId = explode(',',$iCUId);
//        $checkCreators = XhcustInfo::find([
//            'columns' => 'iCreateUserId',
//            'conditions' => 'bDelete=0 AND iCUId in ({ids:array})',
//            'bind' => array('ids' => $iCUId)
//        ]);
//        foreach ($checkCreators  as $checkCreator){
//            if (!User::isAdmin() && $checkCreator->iCreateUserId != Main::getLoginUserInfo('userId') ) {
//                return $this->response->setContent('没有权限');
//            }
//        }
        $this->view->pick('customer/authManage');
        Assets::importJs('js/authManage.js');
        Assets::importJs('js/myMain.js');
        Assets::easyUI();
        Template::exists('authManage', 'list') or die(Main::showMessageModal('配置文件不存在，请先创建！', 109106002));//检查public/template/from/目录下是否都存在template文件夹
        Template::exists('staffList', 'list') or die(Main::showMessageModal('配置文件不存在，请先创建！', 109106002));//检查public/template/from/目录下是否都存在template文件夹
        $listSearchArr = [];
        $listSearchArr[] = array('type' => 'text', 'id' => 'list_search', 'label' => ' 搜索： ');
        $listSearchArr[] = array('type' => 'button', 'id' => 'bt_list_search', 'text' => '查找', 'icon' => 'fa-search', 'style' => 'margin-left:10px');
        $this->view->setVars(array(
            'List' => Template::createList('List', 'authManage', [
//                'buttonToolbar' => Template::createButtonToolBar($listButtonArr)
            ]),
            'staffList' => Template::createList('staffList', 'staffList', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, false),
            ]),
        ));
    }


    /**
     * 保存权限
     * @return string
     *
     * created by dale 2017/9/5 
     */
    public function saveAuthAction()
    {
        $this->view->disable();
        $userIds = $this->request->getPost('userIds', 'string');
        $iCUId = $this->request->getPost('id', 'string');
        if(!$userIds || !$iCUId ){
            return $this->sendErrorResponse(400,'缺少参数');
        }
        $userIds = array_values(array_filter(explode(',',$userIds)));
        try{
            $this->db->begin(); //事务开始
            $iCUIds = explode(',',$iCUId);
            foreach ($iCUIds as $iCUId){
                foreach ($userIds as $iUserId){
                    $auth = XhcustAuth::findFirst([
                        'conditions' => 'bDelete=0 AND iAuthId=:iUserId: AND iCUId=:iCUId:',
                        'bind' => array('iUserId' => $iUserId, 'iCUId' => $iCUId)
                    ]);
                    if(!$auth){
                        $auth=new XhcustAuth();
                    }
                    $auth->iCUId = $iCUId;
                    $auth->iAuthId = $iUserId;
                    if(!$auth->save()){
                        return $this->sendErrorResponse(500,'保存失败');
                    }
                }
            }
            $this->db->commit(); //提交
        }catch (\Exception $e){
            $this->db->rollback(); //回滚
            return $this->sendErrorResponse(500,$e->getMessage());
        }
        return $this->sendSuccessResponse('授权成功');
    }

    /**
     * 获取权限
     *
     * @return string
     *
     */
    public function getAuthAction()
    {
        $iCUId = $this->request->getQuery('id', 'string');
        if(!$iCUId){
            return $this->sendErrorResponse(400,'获取权限');
        }
        $iCUIds = explode(',',$iCUId);
        $builder = $this->modelsManager->createBuilder()
            ->columns('a.iCUAId,a.iCUId,a.iAuthId,a.iCreateUserId,a.tCreateDate,a.tLastModifyDate,a.iLastModifyUserId,s.sStaffName')
            ->addFrom('Admin\Models\crm\XhcustAuth', 'a')
            ->leftJoin('Admin\Models\hrm\XhhrmStaff', 'a.iAuthId=s.iUserId', 's')
            ->where('a.bDelete=0')
            ->andWhere("a.iCUId  in ({ids:array})", array('ids' => $iCUIds));

        $data = Main::runBuilderPaginator($builder, true);
        Main::runUserNameById($data['rows'], 'iCreateUserId', true);
        Main::runUserNameById($data['rows'], 'iLastModifyUserId', true);
        return $this->sendJsonResponse($data);
    }

    /**
     * 删除权限
     *
     * created by dale 2017/8/11
     */
    public function delAuthAction()
    {
        $this->view->disable();
        $ids = $this->request->getPost('ids', 'string');
        if(!$ids){
            return $this->sendErrorResponse(400,'缺少参数');
        }
        try{
            $ids = explode(',', $ids);
            $objs = XhcustAuth::find([
                'conditions' => 'iCUAId in ({ids:array})',
                'bind' => ['ids' => $ids]
            ]);
            $this->db->begin();
            foreach ($objs as $obj) {
                $obj->bDelete = 1;
                if(!$obj->save()){
                    $this->db->rollback();
                    return $this->sendErrorResponse(500,'删除失败');
                }
            }
            $this->db->commit();
            return $this->sendSuccessResponse('删除成功');
        }catch (\Exception $e){
            $this->db->rollback();
            return $this->sendErrorResponse(500,$e->getMessage());
        }


    }

    /**
     * 学生列表
     *
     * create by dale 20171211
     */
    public function staffListAction(){
        $this->view->pick('customer/staffList');
        Assets::importJs('js/staffList.js');
        Assets::importJs('js/myMain.js');
        Assets::easyUI();
        Template::exists('staffList', 'list') or die(Main::showMessageModal('配置文件不存在，请先创建！', 109106002));//检查public/template/from/目录下是否都存在template文件夹
        $this->view->setVars(array(
            'List' => Template::createList('List', 'staffList', []),

        ));

    }

    public function getStaffAction($iCUId){
        if(!$iCUId ){
            return $this->sendErrorResponse(400,'缺少参数');
        }
        $key = $this->request->getPost('key','string');
        $iUserId=Main::getLoginUserInfo('userId');
        $staff=XhhrmStaff::findFirst([
            'conditions'=>'iUserId=:iUserId: AND bDelete=0',
            'bind' => ['iUserId'=>$iUserId],
        ]);
        if(!$staff){
            return $this->sendErrorResponse(500,'找不到该员工职工信息');
        }
        $iDepId=end(array_filter(explode(',',$staff->sDepIds)));
        $iCUIds = explode(',',$iCUId);
        //查询条件
        $conditionArr=[
            'conditions'=>'sDepIds like :iDepId: AND bDelete=0',
            'bind' => ['iDepId'=>'%,'.$iDepId.',%'],
        ];
        if(count($iCUIds) == 1){  //单条记录的处理  实时更新已加入列表的权限
            $authIds=XhcustAuth::find([
                'columns'=>'iAuthId',
                'conditions'=>'iCUId=:iCUId: AND bDelete=0',
                'bind' => ['iCUId'=>$iCUId],
            ]);
            $authIds=array_column($authIds->toArray(),'iAuthId');
            $authIds[]=$iUserId;
            if($authIds!=[]){
                $conditionArr['conditions'].=" AND iUserId not in ({ids:array})";
                $conditionArr['bind'] =array_merge($conditionArr['bind'],array("ids"=>$authIds));
            }
        }
        if($key){  //添加名字查询
            $conditionArr['conditions'].=" AND ( sStaffName like  :key:  OR sSelfPhone like  :key: ) ";
            $conditionArr['bind'] =array_merge($conditionArr['bind'],array("key"=>"%".$key."%"));
        }


        
        $staffs=Main::runModelPaginator('Admin\Models\hrm\XhhrmStaff',$conditionArr,true);

        return $this->sendJsonResponse($staffs);
    }


    public function getCusInfoAction(){
        $iCUId = $this->request->getPost('iCUId');
        $info = XhcustInfo::findFirst([
            'columns'    => 'iCUId,sProvinceName,sCityName,sCountyName,sDetailedAddress',
            'conditions' => 'bDelete = 0 AND iCUId = :iCUId: ',
            'bind'       => ['iCUId' => $iCUId]
        ])->toArray();
        if(isset($info['sProvinceName'])){
            $names = [$info['sProvinceName'],$info['sCityName'],$info['sCountyName']];
            $info['area'] = json_decode($this->getAreaBynamesAction($names),true);
        }else{
            $info['area'] = null;
        }
        return $this->sendJsonResponse($info);

    }


    public function classListAction(){
        $iCUId = $this->request->getQuery('iCUId','int');
        Assets::easyUI();
        Assets::importJs('js/classList.js');
        $this->view->pick('customer/classList');
        Template::exists('classList', 'list') or die(Main::showMessageModal('配置文件不存在，请先创建！', 109106002));
        $listButtonArr = $formButtonArr = $listSearchArr = array();

            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_add', 'text' => '新增', 'icon' => 'fa-plus');


            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_del', 'text' => '删除', 'icon' => 'fa-trash');

        $listSearchArr[] = array('type' => 'text', 'id' => 'list_search', 'label' => ' 搜索： ');
        $listSearchArr[] = array('type' => 'button', 'id' => 'bt_list_search', 'text' => '查找', 'icon' => 'fa-search', 'style' => 'margin-left:10px');
        return $this->view->setVars([
            'List'       => Template::createList('list', 'classList', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, !!$listButtonArr),
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr)
            ]),
            'iCUId'       => $iCUId,
        ]);
    }


    public function classFormAction($iCUId=null,$iCCId=null){
        $this->view->pick('customer/classForm');
        Assets::importJs('js/classForm.js');

        $webArr  = [];
        $webArr['iCUId'] = $iCUId;
        $webArr['iGrade'] = XhsysEnum::getEnumByNodeName('年级');
        if($iCCId){
            $info = XhcustClass::findFirst($iCCId);
            $webArr['info'] = json_encode($info->toArray());
        }

        $this->view->setVars($webArr);
    }

    /**
     * 获取class
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale 20180416
     */
    public function getClassAction($iCUId){
        $key = $this->request->getPost('key','string');
        $builder = $this->modelsManager->createBuilder()
            ->columns('*')
            ->from('Admin\\Models\\crm\\XhcustClass')
            ->where('bDelete = 0 AND iCUId = :iCUId:',['iCUId' => $iCUId] );

        if ($key) {
            $builder->andWhere(' a.sTitle like :key: ',[ 'key' => '%'.$key.'%' ] );
        }

        $data = Main::runBuilderPage($builder,['iGrade'=>XhsysEnum::getEnumByNodeName('年级')]);

        Main::runUserNameById($data['rows'],['iCreateUserId' => 'iCreateUserId','iLastModifyUserId' => 'iLastModifyUserId'],true);
        return $this->sendJsonResponse($data);
    }


    /**
     * 保存
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale 20180416
     */
    public function saveClassAction(){
        $data = $this->request->getPost();
        try{
            if (isset($data['iCCId']) && $data['iCCId'] != '' ) {
                $obj = XhcustClass::findFirst($data['iCCId']);
            } else {
                $obj = new XhcustClass();
            }
            $obj->assign($data);
            if (!$obj->save()) {
                return $this->sendErrorResponse(500,'保存失败');
            }
            return $this->sendSuccessResponse('保存成功');
        }catch (\Exception $e) {
            return $this->sendErrorResponse(500,$e->getMessage());
        }
    }

    /**
     * 删除接口
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * create by dale 20180416
     */
    public function delClassAction(){
        $ids = $this->request->getPost('ids');
        if(!is_array($ids)){
            $ids = explode(',',$ids);
        }
        try{
            $this->db->begin();
            $objs = XhcustClass::find([
                'conditions' => 'iCCId in  ({ids:array}) AND bDelete = 0',
                'bind'       => ['ids' => $ids]
            ]);
            foreach ($objs as $obj) {
                $obj->bDelete = 1;
                if(!$obj->save()){
                    $this->db->rollback();
                    return $this->sendErrorResponse(500,'保存失败');
                }
            }
            $this->db->commit();
            return $this->sendSuccessResponse('保存成功');
        }catch (\Exception $e){
            $this->db->rollback();
            return $this->sendErrorResponse(500,$e->getMessage());
        }
    }

    /**
     * @param $data
     * @return int
     * create by xjq 20180621
     */
    public function custCompleteCheck($data){
        $fields = [
            'sSchoolName','iSchoolId','iLevel','iType','tSchoolDate','tCoopDate',
            'sIntroName','sChargeName','sChargePhone','iGroupId',
            'iMarketId','iOperateId','sProvinceName','sCityName',
            'sCountyName', 'bAgree', 'bWelfare','iAidsLevel','sDetailedAddress'
        ];
        $count = 0;
        foreach ($fields as $field) {
            if (isset($data[$field]) === false || $data[$field] === '' ) {
                $count++;
            }
            if (in_array($field , ['tSchoolDate' , 'tCoopDate']) && $data[$field] == '0000-00-00') {
                $count++;
            }
        }
        $total = count($fields);
        return intval(floatval(($total-$count)/$total)*100);
    }




//    public function testAction(){
//        var_dump(FollowController::jj['type']);
//    }



}
